We can leverage the capabilities of Spring DI engine using the annotations in the org.springframework.beans.factory.annotation
and org.springframework.context.annotation packages
.
We often call these “Spring core annotations” and we’ll review them in this tutorial.
We can use the @Autowired to mark a dependency which Spring is going to resolve and inject. We can use this annotation with a constructor, setter, or field injection.
@Autowired has a boolean argument called required with a default value of true. It tunes Spring’s behavior when it doesn’t find a suitable bean to wire. When true, an exception is thrown, otherwise, nothing is wired.
Note, that if we use constructor injection, all constructor arguments are mandatory. Starting with version 4.3, we don’t need to annotate constructors with @Autowired explicitly unless we declare at least two constructors.
@Bean marks a factory method which instantiates a Spring bean:
@Bean
Engine engine() {return new Engine();
}
Spring calls these methods when a new instance of the return type is required.
The resulting bean has the same name as the factory method. If we want to name it differently, we can do so with the name or the value arguments of this annotation (the argument value is an alias for the argument name):
@Bean("engine")
Engine getEngine() {return new Engine();
}
Note, that all methods annotated with @Bean must be in @Configuration classes.
We use @Qualifier along with @Autowired to provide the bean id or bean name we want to use in ambiguous situations.
For example, the following two beans implement the same interface:
class Bike implements Vehicle {}class Car implements Vehicle {}
If Spring needs to inject a Vehicle bean, it ends up with multiple matching definitions. In such cases, we can provide a bean’s name explicitly using the @Qualifier annotation.
@Autowired
Biker(@Qualifier("bike") Vehicle vehicle) {this.vehicle = vehicle;
}
@Autowired
void setVehicle(@Qualifier("bike") Vehicle vehicle) {this.vehicle = vehicle;
}
Alternatively:
@Autowired
@Qualifier("bike")
void setVehicle(Vehicle vehicle) {this.vehicle = vehicle;
}
@Autowired
@Qualifier("bike")
Vehicle vehicle;
@Required on setter methods to mark dependencies that we want to populate through XML:
@Required
void setColor(String color) {this.color = color;
}
Otherwise, BeanInitializationException will be thrown.
参考:
Spring Core Annotations