Autowired in spring
- Dependency Injection (DI):
Spring's core principle is Dependency Injection (DI), where objects define their dependencies without creating them.
Autowired Annotation:
@Autowired
is a Spring annotation used for automatic injection of bean dependencies.Bean Declaration:
Declare a class as a Spring bean using
@Component
,@Service
, or@Repository
annotations.Component Scan:
Enable component scanning in the configuration to let Spring automatically discover and register beans in the application context.
ApplicationContext:
Create an
ApplicationContext
to manage the Spring beans and their dependencies.Autowired Injection:
Use
@Autowired
on fields, setter methods, or constructors in the dependent class to indicate the need for automatic dependency injection.Constructor Injection:
Prefer constructor injection by annotating the class constructor with
@Autowired
. Spring automatically injects dependencies when the bean is created.Setter Injection:
Use setter methods annotated with
@Autowired
to inject dependencies. This is an alternative to constructor injection.Field Injection:
Annotate class fields directly with
@Autowired
. This approach is concise but has some drawbacks compared to constructor injection.Qualifier Annotation:
- When multiple beans of the same type exist, use
@Qualifier
along with@Autowired
to specify the bean's name to be injected.
- When multiple beans of the same type exist, use
Primary Annotation:
- Mark a primary bean using
@Primary
when multiple beans of the same type exist, indicating it as the primary candidate for injection.
- Mark a primary bean using
Autowired on Methods:
- Annotate methods with
@Autowired
to inject dependencies. This is useful when dealing with non-bean classes.
- Annotate methods with
Autowired with Optional:
- Use
Optional
along with@Autowired
to handle scenarios where the dependency might be missing.
- Use
Autowired with Collections:
- Inject a collection of beans using
@Autowired
on a List, Set, or Map field.
- Inject a collection of beans using
Autowired in XML Configuration:
- In XML configuration, use
<context:component-scan>
and<bean>
elements to achieve autowiring.
- In XML configuration, use
Autowiring Modes:
- Specify autowiring modes using
@Autowired
withrequired
attribute, indicating whether the dependency is mandatory.
- Specify autowiring modes using
Autowiring with Qualifier in XML:
- In XML configuration, use
<qualifier>
to specify the bean name when autowiring by type.
- In XML configuration, use
Custom Qualifier Annotation:
- Create a custom qualifier annotation by extending
@Qualifier
for more meaningful and type-safe autowiring.
- Create a custom qualifier annotation by extending
Autowired with Optional:
- In Spring 4.0 and later, use
@Autowired
on Optional types for more flexible dependency handling.
- In Spring 4.0 and later, use
Conditional Autowiring:
- Use
@ConditionalOn...
annotations to conditionally enable autowiring based on specific conditions.
- Use