You are on page 1of 9

Spring Framework

Annotations
DI-Related Annotations

@Autowired @Bean @Qualifier @Required

@Value @DependsOn @Lazy @Lookup

@Primary @Scope
@Autowired annotation Constructor injection:
class Car {
Engine engine;
@Autowired annotation can be used to mark a
dependency which Spring is going to resolve @Autowired
and inject. This annotation can be used with a Car(Engine engine) {
this.engine = engine;
constructor, setter, or field injection. }
@Autowired has a boolean argument called }

required with a default value of true. It tunes Setter injection:


Spring's behavior when it doesn't find a class Car {
suitable bean to wire. When true, an exception Engine engine;
is thrown, otherwise, nothing is wired.
@Autowired
Note, that if we use constructor injection, all void setEngine(Engine engine) {
this.engine = engine;
constructor arguments are mandatory. }
}
Starting with version 4.3, we don't need to
annotate constructors with @Autowired Field injection:
explicitly unless we declare at least two class Car {
constructors. @Autowired
Engine engine;
}
@Qualifier annotation
In a situation when you create more than For example, the following two beans
one bean of the same type and want to implement the same interface:
wire only one of them with a property, class Bike implements Vehicle {}
you can use the @Qualifier annotation class Car implements Vehicle {}
along with @Autowired to remove the
In such cases, we can provide a bean's name
confusion by specifying which exact bean
explicitly using the @Qualifier annotation.
will be wired.

@Autowired
@Qualifier("bike")
void setVehicle(Vehicle vehicle) {
this.vehicle = vehicle;
}
@Required annotation @Bean annotation
The @Required annotation applies to bean @Bean marks a factory method which instantiates a
property setter methods and it indicates Spring bean:
that the affected bean property must be @Bean
populated in XML configuration file at Engine engine() {
return new Engine();
configuration time. }

Otherwise, the container throws a Spring calls these methods when a new instance of
BeanInitializationException exception. the return type is required.
The resulting bean has the same name as the factory
@Required
void setColor(String color) { method. To name it differently the name or the value
this.color = color; arguments of this annotation can be used (the
} argument value is an alias for the argument name)
@Bean("engine")
<bean class="com.test.annotations.Bike">
Engine getEngine() {
<property name="color" value="green" />
return new Engine();
</bean> }

Note, that all methods annotated with @Bean must


be in @Configuration classes.
@Value annotation
Constructor injection:
Engine(@Value("8") int cylinderCount) {
Spring @Value annotation is used to this.cylinderCount = cylinderCount;
assign default values to variables and }

method arguments. Setter injection:


@Value("8")
We can read spring environment
void setCylinderCount(int cylinderCount) {
variables as well as system variables this.cylinderCount = cylinderCount;
using @Value annotation. }

@Value annotation also supports SpEL. Field injection:


@Value("8")
int cylinderCount;

Wire values defined in external sources:


*.properties file: engine.fuelType=petrol

inject the value of engine.fuelType with the following:


@Value("${engine.fuelType}")
String fuelType;
@Primary annotation @DependsOn annotation
Sometimes we need to define multiple This annotation can be used to make Spring initialize
beans of the same type. If we mark the most other beans before the annotated one.
frequently used bean with @Primary it will We only need this annotation when the
be chosen on unqualified injection points. dependencies are implicit, for example, JDBC driver
@Component loading or static variable initialization.
@Primary
class Car implements Vehicle {} @DependsOn on the dependent class specifying the
names of the dependency beans.
@Component
class Bike implements Vehicle {} @DependsOn("engine")
class Car implements Vehicle {}
@Component
class Driver { If we define a bean with the @Bean annotation, the
@Autowired factory method should be annotated
Vehicle vehicle; Spring injects a Car bean
}
with @DependsOn
@Bean
@Component @DependsOn("fuel")
class Biker { Engine engine() {
@Autowired vehicle will be a Bike object return new Engine();
@Qualifier("bike") because it's qualified }
Vehicle vehicle;
}
@Lazy annotation
By default, Spring creates all singleton beans @Lazy annotation has an argument named value
eagerly at the startup/bootstrapping of the with the default value of true. It is useful to override
application context. However, there are cases the default behavior.
when we need to create a bean when we
request it, not at application startup. For example, marking beans to be eagerly loaded
@Lazy annotation behaves differently when the global setting is lazy, or configure
depending on its location place: specific @Bean methods to eager loading in
• a @Bean annotated bean factory method, to a @Configuration class marked with @Lazy
delay the method call (hence the bean @Configuration
creation) @Lazy
• a @Configuration class and all contained class VehicleFactoryConfig {

@Bean methods will be affected @Bean


• a @Component class, which is not a @Lazy(false)
Engine engine() {
@Configuration class, this bean will be return new Engine();
initialized lazily }
}
• an @Autowired constructor, setter, or field, to
load the dependency itself lazily (via proxy)
@Lookup annotation @Scope annotation
A method annotated with @Lookup tells @Scope uses to define the scope of
Spring to return an instance of the a @Component class or a @Bean definition.
method's return type when we invoke it. It can be either singleton, prototype, request,
Essentially, Spring will override session, globalSession or some custom scope.
annotated method and use method's
return type and parameters as @Component
arguments to BeanFactory#getBean. @Scope("prototype")
class Engine {}
@Lookup is useful for:
• Injecting a prototype-scoped bean into
a singleton bean (similar to Provider)
• Injecting dependencies procedurally
@Lookup is the Java equivalent of the
XML element lookup-method.

You might also like