Spring Dependency Injection Autowiring Null [dupli

2020-01-31 01:50发布

问题:

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

回答1:

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"/>


回答2:

Just to add further to Jeha's correct answer.

Currently, by doing

Bridge wb = new Bridge();

Means that, that object instance is not "Spring Managed" - I.e. Spring does not know anything about it. So how can it inject a dependency it knows nothing about.

So as Jeha said. Add the @Service annotation or specify it in your application context xml config file (Or if you are using Spring 3 you @Configuration object)

Then when the Spring context starts up, there will be a Singleton (default behavior) instance of the Bridge.class in the BeanFactory. Either inject that into your other Spring-Managed objects, or pull it out manually e.g.

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

Now it will have the dependencies wired in.



回答3:

If you want to use new operator and still all dependency injected, then rather than making this a spring component (by annotating this with @Service), make it a @Configurable class.

This way even object is instantiated by new operator dependencies will be injected.

Few configuration is also required. A detailed explanation and sample project is here.

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