Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring dependency injection with @Autowired annotation without setter

I'm using Spring since a few months for now, and I thought dependency injection with the @Autowired annotation also required a setter for the field to inject.

So, I am using it like this:

@Controller public class MyController {      @Autowired     MyService injectedService;      public void setMyService(MyService injectedService) {         this.injectedService = injectedService;     }      ... 

}

But I've tried this today:

@Controller public class MyController {      @Autowired     MyService injectedService;      ... 

}

And oh surprise, no compilation errors, no errors at startup, the application is running perfectly...

So my question is, is the setter required for dependency injection with the @Autowired annotation?

I'm using Spring 3.1.1.

like image 390
Tony Avatar asked Apr 13 '12 12:04

Tony


People also ask

Is @autowired setter injection?

@Autowired on Setter MethodsYou can use @Autowired annotation on setter methods to get rid of the <property> element in XML configuration file. When Spring finds an @Autowired annotation used with setter methods, it tries to perform byType autowiring on the method.

Can we use @autowired without @component?

So the answer is: No, @Autowired does not necessarily mean you must also use @Component . It may be registered with applicationContext. xml or @Configuration+@Bean .

Is @autowired used for dependency injection?

Spring @Autowired annotation is used for automatic dependency injection. Spring framework is built on dependency injection and we inject the class dependencies through spring bean configuration file.

Can we use @autowire without using Spring boot context?

Sure you can use @Autowired but as your JobMain isn't a a Spring bean it will ofcourse not be autowired. Basically that is duplicate of this (more reasons here. So to fix make your JobMain an @Component and don't construct a new instance yourself.


1 Answers

You don't need a setter with the @Autowired, the value is set by reflection.

Check this post for complete explanation How does Spring @Autowired work

like image 120
Arnaud Gourlay Avatar answered Oct 14 '22 10:10

Arnaud Gourlay