【问题标题】:Spring Dependency Injection Autowiring Null [duplicate]Spring依赖注入自动装配空[重复]
【发布时间】:2011-12-26 19:59:03
【问题描述】:

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

public class Bridge {

    private final String BASE_URL = "http://localhost:8080/u";

    @Autowired
    RestTemplate restTemplate;

    public void addW() {
       Map<String, String> x = new HashMap<String, String>();
       W c = restTemplate.getForObject(BASE_URL + "/device/yeni", W.class, x);
       System.out.println("Here!");
    }
}

在另一堂课上我称之为:

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

我是 Spring 和依赖注入术语的新手。我的 restTemplate 变量为 null 并引发异常。怎么解决(不知道是不是和我用new关键字有关)?

【问题讨论】:

  • 这个问题对于 Spring 新手来说太常见了,我在spring 标签 wiki 中添加了对这个问题的引用。到目前为止,我 100% 确定它已被多次回答,但我找不到任何合理的问题。如果你们中的任何人找到了,请将此问题标记为重复并更新 wiki。

标签: java spring dependency-injection autowired


【解决方案1】:

使用Bridge wb = new Bridge() 不适用于依赖注入。你的 restTemplate 没有被注入,因为 wb 不是由 Spring 管理的。

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

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

或通过 bean 声明:

<bean id="bridge" class="Bridge"/>

【讨论】:

  • 感谢您的评论。我该如何设计我的实现你有什么建议吗?
【解决方案2】:

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

目前,通过做

Bridge wb = new Bridge();

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

正如杰哈所说。添加@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

现在它将有依赖关系。

【讨论】:

  • 我在另一个课程中使用了Service 注释和自动装配的 Bridge 课程。 Service 和 Configuration 有什么区别?
  • @Configuration 允许以编程方式指定您的 bean。它不是像 @Service/@Repositry/@Component/@Controller 这样的刻板印象。另外,您将需要 - 在您的应用程序上下文中
【解决方案3】:

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

这样,即使对象被新的操作符实例化,依赖也会被注入。

也需要很少的配置。详细的解释和示例项目是here。

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

【讨论】:

  • 您是否与您所链接的网站有关联?
  • @Andrew 这个博客是公开的并且是我自己写的,我不认为这需要任何从属关系。我没有得到你的关注。
  • 每次链接到自己的网站时,要求披露。
  • @Andrew 我需要采取什么行动?
  • 请务必仔细阅读FAQ on Self-Promotion。
猜你喜欢
  • 1970-01-01
  • 2013-05-01
  • 2013-05-03
  • 2012-10-27
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 1970-01-01
相关资源
最近更新 更多