Spring 依赖注入自动装配 Null [英] Spring Dependency Injection Autowiring Null

查看:42
本文介绍了Spring 依赖注入自动装配 Null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 和依赖注入术语的新手.我的 restTemplate 变量为空并引发异常.我该怎么办怎么解决(不知道是不是和我使用了new关键字有关)?

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() 不适用于依赖注入.你的 restTemplate 没有被注入,因为 wb 不是由 Spring 管理的.

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 声明:

or by bean declaration:

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

这篇关于Spring 依赖注入自动装配 Null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆