Spring Core Annotations List


Here you will know about  all  Spring core related annotations which leverage the capabilities of Spring DI engine using annotations  in the org.springframework.beans.factory.annotation and org.springframework.context.annotation packages. I have categorize Sping core annotations in two categories:

  1. DI (Dependency Injection) Related Annotations
  2. Context Configuration Annotations

See Also :

DI Related Annotations

@Bean

@Bean marks as factory method which instantiates a Spring bean. Spring calls these methods when a new instance of the return type is required. Bean will have same name as factory method.

@Bean
Engine engine() {
    return new Engine();
}

If you want to name it differently, we can do so with the name of the value arguments of this annotation.

@Bean("engine")
Engine getEngine() {
    return new Engine();
}

Note : All these @Bean annotated methods must be in @Configuration classes.

@Autowired

@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.

Constructor injection:

class Car {
    Engine engine;

    @Autowired
    Car(Engine engine) {
        this.engine = engine;
    }
}

Setter injection:

class Car {
    Engine engine;

    @Autowired
    void setEngine(Engine engine) {
        this.engine = engine;
    }
}

Field injection:

class Car {
    @Autowired
    Engine engine;
}

Note :

  • @Autowired has a boolean argument called required with a default value of true. If fields is autowired and Spring’s not find any suitable bean to wire then it will throw an exception to handle such case make Autowire as required false.
  • After version 4.3, we don’t need to annotate constructors with @Autowired explicitly unless we declare at least two constructors.

@Qualifier

@Qualifier use along with @Autowired to provide the bean id or bean name we want to use in ambiguous situations. For example :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. To resolve such ambiguity , we can provide a bean’s name explicitly using the @Qualifier annotation.
Using constructor injection:

@Autowired
Biker(@Qualifier("bike") Vehicle vehicle) {
    this.vehicle = vehicle;
}

Using setter injection:

@Autowired
void setVehicle(@Qualifier("bike") Vehicle vehicle) {
    this.vehicle = vehicle;
}

or

@Autowired
@Qualifier("bike")
void setVehicle(Vehicle vehicle) {
    this.vehicle = vehicle;
}

Using field injection:

@Autowired
@Qualifier("bike")
Vehicle vehicle;

@Required

@Required on setter methods to mark dependencies that we want to populate through XML.

@Required
void setColor(String color) {
    this.color = color;
}

<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

Otherwise, BeanInitializationException will be thrown.

@Value

@Value use as placeholder for injecting property values into beans. It’s compatible with constructor, setter, and field injection.
Constructor injection:

Engine(@Value("10") int cylinderCount) {
    this.cylinderCount = cylinderCount;
}

Setter injection:

@Autowired
void setCylinderCount(@Value("10") int cylinderCount) {
    this.cylinderCount = cylinderCount;
}

or

@Value("10")
void setCylinderCount(int cylinderCount) {
    this.cylinderCount = cylinderCount;
}

Field injection :

@Value("10")
int cylinderCount;

Placeholder from properties file : We can use placeholder strings in @Value to wire values defined in external sources, for example, in .properties or .yaml files.
Let’s assume the following .properties file having below value:

engine.fuelType=diesel

We can inject the value of engine.fuelType with the following:

@Value("${engine.fuelType}")
String fuelType;

We can use @Value even with SpEL.

@DependsOn

@DependsOn annotation use to initialize other beans before the annotated one. Usually, this behavior is automatic, based on the explicit dependencies between beans. @DependsOn use when the dependencies are implicit. For example : JDBC driver loading or static variable initialization.

@DependsOn  annotations need an array containing the dependency bean names.

@DependsOn("engine")
class Car implements Vehicle {}

Alternatively, if we define a bean with the @Bean annotation, the factory method should be annotated with @DependsOn:

@Bean
@DependsOn("fuel")
Engine engine() {
    return new Engine();
}

@Lazy

@Lazy  annotations use when  need to initialize our bean lazily when we request it. By default all singleton beans create eagerly at the startup/bootstrapping of the application context.

@Lazy annotation behaves differently depending on where we exactly place it :

  • A @Bean annotated bean factory method, to delay the method call (hence the bean creation).
  • A @Configuration class and all contained @Bean methods will be affected
  • A @Component class, which is not a @Configuration class, this bean will be initialized lazily.
  • An @Autowired constructor, setter, or field, to load the dependency itself lazily (via proxy).

By Default @Lazy annotation value is true. It is useful to override  the default behavior.
For example :

  • Marking beans to be eagerly loaded when the global setting is lazy.
  • Configure specific @Bean methods to eager loading in a @Configuration class marked with @Lazy.
@Configuration
@Lazy
class VehicleFactoryConfig {

    @Bean
    @Lazy(false)
    Engine engine() {
        return new Engine();
    }
}

@Lookup

@Lookup annotated method tells Spring to return an instance of the method’s return type when we invoke it.

@Primary

@Primary annotation use to make specified bean as default when define multiple beans of same type. Otherwise beans which are not having @Qualifier then injection will be unsuccessful because Spring has no clue which bean we need.
We can use @Primary to simplify this case: if we mark the most frequently used bean with @Primary it will be chosen on unqualified injection points.

@Component
@Primary
class Car implements Vehicle {}

@Component
class Bike implements Vehicle {}

@Component
class Driver {
    @Autowired
    Vehicle vehicle;
}

@Component
class Biker {
    @Autowired
    @Qualifier("bike")
    Vehicle vehicle;
}

In the previous example Car is the primary vehicle. Therefore, in the Driver class, Spring injects a Car bean. Of course, in the Biker bean, the value of the field vehicle will be a Bike object because it’s qualified.

@Scope

@Scope annotation use to define the scope of a @Component class or a @Bean definition. It can be either singleton, prototype, request, session, globalSession or some custom scope. By default scope of bean is singleton.
For example:

@Component
@Scope("prototype")
class Engine {}

Context Configuration Annotations

We can configure the application context with the annotations described in this section.

@Profile

When we want to use a specific @Component class or a @Bean method only when a specific profile is active, we can mark it with @Profile. We can configure the name of the profile with the value argument of the annotation:

@Component
@Profile("sportDay")
class Bike implements Vehicle {}

@Import

We can use specific @Configuration classes without component scanning with this annotation. We can provide those classes with @Import‘s value argument:

@Import(VehiclePartSupplier.class)
class VehicleFactoryConfig {}

@ImportResource

We can import XML configurations with this annotation. We can specify the XML file locations with the locations argument, or with its alias, the value argument:

@Configuration
@ImportResource("classpath:/annotations.xml")
class VehicleFactoryConfig {}

@PropertySource

With this annotation, we can define property files for application settings:

@Configuration
@PropertySource("classpath:/annotations.properties")
class VehicleFactoryConfig {}

@PropertySource leverages the Java 8 repeating annotations feature, which means we can mark a class with it multiple times:

@Configuration
@PropertySource("classpath:/annotations.properties")
@PropertySource("classpath:/vehicle-factory.properties")
class VehicleFactoryConfig {}

@PropertySources

We can use this annotation to specify multiple @PropertySource configurations:

@Configuration
@PropertySources({
    @PropertySource("classpath:/annotations.properties"),
    @PropertySource("classpath:/vehicle-factory.properties")
})
class VehicleFactoryConfig {}

Note: After Java 8+ we can achieve the same with the repeating annotations feature as described above.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s