- Building Applications with Spring 5 and Vue.js 2
- James J. Ye
- 81字
- 2025-04-04 16:05:52
Setter-based/method-based injection
The second way is to declare a method, usually a setter, and apply the @Autowired annotation or the @Required annotation to it. For example, we can remove the MessageService constructor and add a setRepository(MessageRepository) method, as follows:
public class MessageService {
...
@Required
public void setRepository(MessageRepository repository) {
this.repository = repository;
}
...
}
Or, you can name it something else, such as the following:
@Autowired
public void prepare (MessageRepository repository) {
this.repository = repository;
}