Usage of @Autowired
- Constructor injection
@Autowired
public TransferServiceImpl(AccountRepository repository){..}
- Method
@Autowired
public void setAccountRepository(AccountRepository)
- Field injection (discouraged)
@Autowired
private AccountRepository accountRepository;
By default autowired beans are required but this be changed: @Autowired(required=false)
Optional is also supported:
@Autowired
public void setAccountService(Optional<AccountService> optAccountService){..}
Disambiguation
@Qualifier is used for disambiguation, can be used both for components and beans (names).
@Autowired
public TransferServiceImpl(@Qualifier("jdbc") AccountRepository ar){ ..}
@Component("jdbc")
public class MyJDBCAccountRepositoryImp{
..}
Autowiring resolution rules:
- look for unique bean of request type
- use @Qualifier if present
- try to find bean matching by name
Configuration choices
If a class has only a default constructor -> no need to annotate with @Autowired
if class had only one non-default constructor -> no need to annotate with @Autowired
if class has more than one constructor -> Spring will call zero-argument by default or @Autowired must be used
Constructor vs setter
Constructor
– mandatory dependencies
– dependencies can be immutable
– concise
Setter
– can allow for circular dependencies
– dependencies are mutable
– can be verbose
– inherit automatically
Lazy beans
This annotation can be used on class, field, constructor and method.
If @Lazy is present on @Component or @Bean and set to true then the @Component and @Bean would not be initialized until referenced by another bean or explicitly retrieved from bean factory. It can take true and false values.
The @Lazy can also be used on classes annotated with @Configuration. If present on @Configuration class then all @Bean methods within @Configuration class are initialized lazily
https://medium.com/@javalearners/spring-boot-annotations-2-3e318b8d18bf
@Component("myService")
@Lazy(true)
public class MyServiceImpl implements MyService{
...
}
@Configuration
public class ApplicationConfig{
@Autowired
@Lazy(true)
public MyService getMyService(){
..
}
}