Loading

Quipoin Menu

Learn • Practice • Grow

spring / Autowiring in Spring
interview

Q1. What is autowiring in Spring?
Autowiring is a feature where Spring automatically injects dependencies into a bean without explicit configuration. It can be done by type, by name, or by constructor. It reduces the need for manual wiring and makes configuration simpler.

Q2. What are the different autowiring modes?
In XML, autowiring modes: no (default), byName (matches property name with bean id), byType (matches property type with a bean), constructor (similar to byType but for constructor arguments), and autodetect (deprecated). In annotation-driven, @Autowired is used for byType autowiring with @Qualifier for byName.

Q3. What is the difference between @Autowired and @Resource?
@Autowired is Spring-specific and wires by type. @Resource is a JSR-250 annotation that wires by name by default, falling back to type. @Resource can be used with name attribute to specify the bean name. Both can be used for dependency injection.

Q4. How does @Qualifier work with @Autowired?
When multiple beans of the same type exist, @Autowired alone cannot decide which to inject. @Qualifier specifies the bean name to be used. Example:
@Autowired @Qualifier("userDaoJdbc") private UserDao userDao;

Q5. Can you use autowiring with constructor injection?
Yes, you can annotate a constructor with @Autowired, and Spring will autowire the constructor parameters by type. Since Spring 4.3, if a class has a single constructor, @Autowired is optional. This is the recommended way for mandatory dependencies.