在Java世界中有个约定(Convention),那就是属性的设置和获取的方法名一般是:set+属性名(参数)及get+属性名()的方式。boolean类型稍有不同,可以使用is+属性名()方式来获取。
以下是一个示例。
public class MessageHandler { private MessageService messageService; public MessageService getMessageService() { return messageService; } public void setMessageService(MessageService messageService) { this.messageService = messageService; } public String handle() { return messageService.sendService(); }}
使用Setter方法注入如下所示。
如果property的name为messageService,那么必须在类中有个叫做setMessageService
的方法,这样才能完成注入。如果将MessageHandler.java中的setMessageService
方法改为setMessageService1
,那么注入就会失败,失败message如下所示。
...java.lang.IllegalStateException: Failed to load ApplicationContext...Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageHandler' defined in class path resource [spring-context.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'messageService' of bean class [huangbowen.net.DependecyInjection.SetterInjection.MessageHandler]: Bean property 'messageService' is not writable or has an invalid setter method. Did you mean 'messageService1'?...
via:http://www.cnblogs.com/huang0925/p/3606382.html