spring autowire注入失败

autowire注入失败, 导致此错误的最主要原因,是因为new的操作符导致。

举个例子

//第一个类
public class Test {

@Autowired
private Testbean testbean;

}


//第二个类, 引用第一个类
public class AnotherTest{

public static main()
{
Test test = new Test(); // 此时, test中的testbean不会自动注入,因为使用了new操作符导致。
}
}

 

注意: 大家可以注意到我们在@controller 中 的 @autowired 却可以正确注入。 这是因为@controller 被spring是自动加载的, 容器并不是以new的方式获取到controller。

好吧,解决此问题的三种方法。

1. 直接注入bean。 这时候比如我们可以将service 中需要autowired的成员 放入到 controller中。
2. Use @Configurable http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-atconfigurable 本人才浅,也无法看明白。 大家可以自己学习。 基于aop的方法。
3. 手动查找bean (从spring bean 工厂获取bean), 不使用new便是了。

http://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null

此篇文章已被阅读4550 次

One Comment

Add a Comment

邮箱地址不会被公开。 必填项已用*标注