16-Annotation-Driven Configuration Flashcards
What happens if auto-wiring a non-existing bean?
NoSuchDefinitionException thrown
What injection modes are supported via @Autowired?
- Field
- Constructor
- ## Setter/method methodNote: although you can auto-wire methods other than setters, this is probably not a good idea, because you are starting to run code during start-up
With constructor, in what case we can drop @Autowired?
If it’s the only constructor in the component
How to inject an optional bean?
Using @Autowired(required = false)
What is the recommended place to check if an optional bean has been set or not?
In @PostConstruct void method() {}
When should use setter DI?
- Circulate dependencies
2. Want subclass to inherited parent’s setters automatically
When should use constructor DI?
- Mandatory dependencies
- Immutable
Constructor injection is generally preferred
Given 2 beans that implement the same service interface e.g. UserService.
Inject bean with @Autowired void method(UserService)
What happens? How to fix it?
- NoSuchDefinitionException because of 2 beans with the same type
- Using void method(@Qualifier(“name”) UserService)
What are the resolution rules for @Autowired?
- First, search by type
- If there are multiple beans of the same type, it looks for @Qualifier
- Match by bean-name and field-name
What is the equivalent @Autowired in JSR-330?
@Resource
What are the resolution rules for @Resource in JSR-250?
Name first, falling back to type if required.
Can @Resource use in constructor DI?
@Resource cannot be used on a constructor.
What is the bean name for the following cases?
- @Service class UserServiceImpl implements UserService {}
- @Bean UserService myUserService() {}
- userServiceImpl
2. myUserService
How to auto-wire a property to the constructor parameter?
@Autowired
MyConstructor(@Value(“${property}”) property) {}
When is a @Lazy bean created?
- When dependency injected
2. By ApplicationContext.getBean() method