Insert a field using @Inject in Spring

I have weird behavior when running @Inject in Spring. This example works well:

 @Controller @RequestMapping("/") public class HomeController { @Autowired private SomeBean someBean; @RequestMapping(method = GET) public String showHome() { System.out.println(someBean.method()); return "home"; } } 

But if I replaced @Autowired with @Inject , the showHome method will throw a NullPointerException because someBean is null . Same thing with setter injection. But with constructor injection, both @Autowired and @Inject work well.

Why is this happening?

I am using Spring 4.3.1. My dependencies in pom.xml are as follows:

 <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> <dependencies> 
+5
source share
1 answer

Spring supports standard JSR-330 annotations, you just need to put the appropriate jars in your classpath. If you are using maven, add the following to your pom.xml :

 <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> 

Why does the constructor injector work?

Like Spring 4.3 , you no longer need to specify @Autowired annotation if the target bean defines only one constructor . Since you have only one constructor, the required dependencies will be inserted no matter what annotation you use.

Also check out this post on why field injection of evil .

+4
source

All Articles