- Building Applications with Spring 5 and Vue.js 2
- James J. Ye
- 89字
- 2025-04-04 16:05:52
Constructor-based injection
As its name suggests, this type of injection is done through the constructors. And, in our Messages App, a MessageRepository bean is injected into a MessageService bean through the constructor. We can apply the @Autowired annotation to the constructor, as follows:
@Autowired
public MessageService (MessageRepository repository) {
this.repository = repository;
}
We can also omit the @Autowired annotation here and Spring still understands that it needs to inject a MessageRepository bean, thereby checking the MessageService constructor and finding out the types of the arguments.