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.
@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.
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 .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With