弹簧依赖注射自动装配空 [英] Spring Dependency Injection Autowiring Null
问题描述
我可以使用RestTemplate并自动连线。然而,我想将我的休息模板相关的部分代码移动到另一个类中,如下所示:
I was able to use RestTemplate and autowire it. However I want to move my rest template related part of code into another class as follows:
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!");
}
}
而在另一个类中,我称之为:
And at another class I call it:
...
Bridge wb = new Bridge();
wb.addW();
...
我是Spring和Dependency Injection术语的新手。我的 restTemplate
变量为null并抛出异常。我可以做什么如何解决它(我不知道它是否与我使用新的
关键字相关)?
I am new to Spring and Dependency Injection terms. My restTemplate
variable is null and throws an exception. What can I do it how to solve it(I don't know is it related to I use new
keyword)?
推荐答案
使用 Bridge wb = new Bridge()
不适用于依赖注入。由于 wB
未被Spring管理,所以 restTemplate
不会被注入。
Using Bridge wb = new Bridge()
does not work with dependency injection. Your restTemplate
is not injected, because wb
in not managed by Spring.
您必须使您的 Bridge
一个Spring bean本身,例如通过注释:
You have to make your Bridge
a Spring bean itself, e.g. by annotation:
@Service
public class Bridge {
// ...
}
或通过bean声明:
<bean id="bridge" class="Bridge"/>
这篇关于弹簧依赖注射自动装配空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!