Tag Archives: import

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 categorized 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 are autowired and Spring’s not found 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 a placeholder for injecting property values into beans. It’s compatible with a 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 uses 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 we 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 the 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, global session or some custom scope. By default scope of bean is a 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.

How to create Maven Java Console Project?


In this below example will show you create maven java project from console and import to eclipse.

Maven provide maven-archetype-quickstart archetype artifact to create console based java project from command prompt.

Pre-Requisite

Go to directory/ workspace where you want to create maven Java project. Below is command to create it.

mvn archetype:generate -DgroupId=com.{group}.app -DartifactId={App Name} -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Example :

mvn archetype:generate -DgroupId=com.facingissuesonit.app -DartifactId=test-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Because we are creating our first project with maven that’s why it will download lots of jars and dependency from maven repository.

C:\Users\facingissuesonit\workspace-sample>mvn archetype:generate -DgroupId=com.facingissuesonit.app -DartifactId=test-app -DarchetypeArtifactId=maven-archetype
-quickstart -DinteractiveMode=false

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:3.0.1:generate (default-cli) > generate-sources @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:3.0.1:generate (default-cli) < generate-sources @ standalone-pom <<<
[INFO]
[INFO] --- maven-archetype-plugin:3.0.1:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Batch mode
[WARNING] No archetype found in remote catalog. Defaulting to internal catalog
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: basedir, Value: C:\Users\facingissuesonit\workspace-sample
[INFO] Parameter: package, Value: com.facingissuesonit.app
[INFO] Parameter: groupId, Value: com.facingissuesonit.app
[INFO] Parameter: artifactId, Value: test-app
[INFO] Parameter: packageName, Value: com.facingissuesonit.app
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: C:\Users\facingissuesonit\workspace-sample\test-app
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 24.133 s
[INFO] Finished at: 2017-06-06T03:55:59-04:00
[INFO] Final Memory: 14M/148M
[INFO] ------------------------------------------------------------------------

Above example command will create project with name test-app in your current directory and will show directory structure as below.

Test-app
-src
--main
---java
----com
-----facingissuesonit
------app
-------App.java
--test
---java
----com
-----facingissuesonit
------app
-------AppTest.java
-pom.xml

Project pom.xml will have entry as below.


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.facingissuesonit.app</groupId>
  <artifactId>test-app</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>test-app</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

Build Project : Go to project directory and run below command to build your project. It will go through all these steps to complete build life cycle as you can see from console logs.

1. validate
2. generate-sources
3. process-sources
4. generate-resources
5. process-resources
6. compile
7. test

mvn package

C:\Users\facingissuesonit\workspace-sample\test-app>mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building test-app 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ test-app ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\Users\facingissuesonit\workspace-sample\test-app\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ test-app ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to C:\Users\facingissuesonit\workspace-sample\test-app\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ test-app ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\Users\facingissuesonit\workspace-sample\test-app\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ test-app ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to C:\Users\facingissuesonit\workspace-sample\test-app\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ test-app ---
[INFO] Surefire report directory: C:\Users\facingissuesonit\workspace-sample\test-app\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.facingissuesonit.app.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.007 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ test-app ---
[INFO] Building jar: C:\Users\facingissuesonit\workspace-sample\test-app\target\test-app-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.372 s
[INFO] Finished at: 2017-06-06T04:07:45-04:00
[INFO] Final Memory: 16M/145M
[INFO] ------------------------------------------------------------------------

Now our build is successful. We can use below command in target folder to run test-app project.

C:\Users\facingissuesonit\workspace-sample\test-app\target>java -cp test-app-1.0-SNAPSHOT.jar com.facingissuesonit.app.App
Hello World!

Import to Eclipse : To import this project in eclipse first we need to convert this project according to eclipse and then import it.

  • Convert to Eclipse Maven Project : Use below command
    mvn eclipse:eclipse
C:\Users\facingissuesonit\workspace-sample\test-app>mvn eclipse:eclipse
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building test-app 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> maven-eclipse-plugin:2.10:eclipse (default-cli) > generate-resources @ test-app >>>
[INFO]
[INFO] <<< maven-eclipse-plugin:2.10:eclipse (default-cli) < generate-resources @ test-app <<< [INFO] [INFO] --- maven-eclipse-plugin:2.10:eclipse (default-cli) @ test-app --- [INFO] Using Eclipse Workspace: C:\Users\facingissuesonit\workspace-sample [WARNING] Workspace defines a VM that does not contain a valid jre/lib/rt.jar: C:\Program Files\Java\jre1.8.0_73 [INFO] Adding default classpath container: org.eclipse.jdt.launching.JRE_CONTAINER [INFO] Not writing settings - defaults suffice [INFO] Wrote Eclipse project for "test-app" to C:\Users\facingissuesonit\workspace-sample\test-app. [INFO] [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 2.717 s [INFO] Finished at: 2017-06-06T04:56:14-04:00 [INFO] Final Memory: 12M/114M [INFO] ------------------------------------------------------------------------ 

Import in Eclipse : Follow below steps to import test-app project in Eclipse

Eclipse File -> Import -> General-> Existing Project in Workspace -> Select Project test-app

Maven Java Console Project