Springdependency injection自动assembly空

我能够使用RestTemplate并自动assembly它。 但是,我想将我的其余模板相关的代码部分移动到另一个类中,如下所示:

public class Bridge { private final String BASE_URL = "http://localhost:8080/u"; @Autowired RestTemplate restTemplate; public void addW() { Map x = new HashMap(); W c = restTemplate.getForObject(BASE_URL + "/device/yeni", W.class, x); System.out.println("Here!"); } } 

在另一个class级我称之为:

 ... Bridge wb = new Bridge(); wb.addW(); ... 

我是Spring和dependency injection术语的新手。 我的restTemplate变量为null并抛出exception。 我能做些什么来解决它(我不知道它与我使用new关键字有关)?

使用Bridge wb = new Bridge()不能用于dependency injection。 你的restTemplate没有注入,因为wb不是由Spring管理的。

你必须使你的Bridge成为一个Spring bean本身,例如通过注释:

 @Service public class Bridge { // ... } 

或通过bean声明:

  

只是为了进一步补充Jeha的正确答案。

目前,通过做

 Bridge wb = new Bridge(); 

意味着,该对象实例不是“Spring Managed” – 即Spring对此一无所知。 那么它怎么能注入一个它一无所知的依赖。

正如Jeha所说。 添加@Service注释或在应用程序上下文xml配置文件中指定它(或者如果您使用的是Spring 3 @ Configuration对象)

然后,当Spring上下文启动时,BeanFactory中将有一个Bridge.class的Singleton(默认行为)实例。 将其注入到其他Spring-Managed对象中,或者手动将其拉出,例如

 Bridge wb = (Bridge) applicationContext.getBean("bridge"); // Name comes from the default of the class 

现在它将连接依赖关系。

如果你想使用new运算符并且仍然注入所有依赖项,那么不要将它作为spring组件(通过使用@Service注释),使其成为@Configurable类。

这种方式甚至可以通过注入新的运算符依赖关系来实例化对象。

几乎没有配置。 这里有详细的解释和示例项目。

http://spring-framework-interoperability.blogspot.in/2012/07/spring-managed-components.html