
上QQ阅读APP看书,第一时间看更新
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.