在学习spring自动装配的时候,发现一个问题,在某些情况下自动装配会找不到bean。
首先在正常情况下,spring可以正常自动装配:
public class Hello {
public String hello(){
return "hello world";
}
}
public class XiaoMing {
private Hello hello;
public XiaoMing(){}
public XiaoMing(Hello hello) {
this.hello = hello;
}
public String sayHello() {
return hello.hello();
}
public void setHello(Hello hello) {
this.hello = hello;
}
public Hello getHello() {
return hello;
}
}
public class Application {
public static void main(String[] args) {
GenericApplicationContext context = new GenericApplicationContext();
new XmlBeanDefinitionReader(context).loadBeanDefinitions("autowiring.xml");
context.refresh();
XiaoMing xiaoMing = context.getBean("xiaoMing", XiaoMing.class);
System.out.println(xiaoMing.sayHello());
}
}
<bean id="hello" class="com.nnkomatsu.Hello"/>
<bean id="xiaoMing" class="com.nnkomatsu.dependencyInjection.XiaoMing" autowire="byName"/>
此时运行结果一切,可以正常返回hello world。
但是当修改了依赖的的getter之后,就出现了一点问题,有时候无法正常装配,有时候又可以:
比如我把XiaoMing类改成以下这样:
public class XiaoMing {
private Hello hello;
public XiaoMing(){}
public XiaoMing(Hello hello) {
this.hello = hello;
}
public String sayHello() {
return hello.hello();
}
public void setHello(Hello hello) {
this.hello = hello;
}
public String getHello() {
return "hello";
}
}
就只是修改了getHello的返回值,此时运行后就出现问题了,没有正常装配上hello对象:
然后我又试了让getHello返回一些其它返回值,发现当返回一些java内置的类时,自动装配就会出问题,但是有些又没问题:
//失败
public Date getHello(){
return new Date();
}
//正常
public List<?> getHello(){
return new ArrayList<>();
}
//正常
public ApplicationContext getHello(){
return new ClassPathXmlApplicationContext();
}
我感觉这种自动装配应该跟setter有关吧,不知道为啥getter也会影响自动装配,而且还有时候正常有时候不正常,求解答。