Spring Dependency Injection Autowiring Null

kamaci picture kamaci · Nov 11, 2011 · Viewed 29.2k times · Source

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();
...

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)?

Answer

jeha picture jeha · Nov 11, 2011

Using Bridge wb = new Bridge() does not work with dependency injection. Your restTemplate is not injected, because wb in not managed by Spring.

You have to make your Bridge a Spring bean itself, e.g. by annotation:

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

or by bean declaration:

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