Constructor Injection
@Autowired
public AppServiceImpl(AppRepository appRepository) {
this.appRepository = appRepository;
}
Method Injection
@Autowired
public setRepository(AppRepository appRepository) {
this.appRepository = appRepository;
}
Field Injection
Not recommended. Hard to unit test.
@Autowired
private AppRepository appRepository;
Optional dependencies
Only inject if dependency exists:
@Autowired(required=false)
AppService appService;
public void method() {
if(appService != null) {
...
}
}
Using Optional:
@Autowired
Optional<AppService> appService;
public void method() {
appService.ifPresent(s -> {
...
});
}
Qualifier Annotation
When component names are not specified, they are auto-generated. When specified, they allow disambiguation if more than one bean class implements the same interface.
@Component
public class AppServiceImpl implements AppService {
@Autowired
public AppServiceImpl(@Qualifier("jdbcRepository") AppRepository appRepository) {
this.appRepository = appRepository;
}
}
@Component("jdbcRepository")
public class JdbcRepositoryImpl implements AppRepository {
...
}
Top comments (2)
What are the advantages of autowiring? Would you recommended annotation configuration against xml configuration?
Autowiring requires less code, reduces development time, and is cleaner. XML configuration is a cumbersome and outdated form of configuration.