CodeIn House

  • Laravel
  • WordPress
  • jQuery
  • Javascript
  • Contact
Home   JAVA   Annotations Based Configuration in Spring Framework

Annotations Based Configuration in Spring Framework

September 15, 2022 by SNK

Java Annotation Based Configuration in Spring Framework

Recently, we did a tutorial on spring xml based configuration which helped us to do configure our project completely with xml. Today we are going to lean annotation based configuration in spring which will help us reduce the line of code we need to write inside our xml file.

We can make use of java annotations for creation of Bean, depedency injection, setter injection as well as field injection which is mostly widely used nowadays. It makes extremly easy to use java annotation for your spring project configuration because it reduces lot of boiler plate code. So, let’s see how to configure your spring project with java annotations.

Let’s get started

What are we going to do ?

  1. Add Component Scanning in XML.
  2. Add @Component annotation to the Java class
  3. Bean Scope.
  4. Depedency Injection using @Autowired Annotation.
  5. Injecting values to the properties.

1. Add Componeny Scanning in XML

To make use of java annotation first you have to enable component scanning. Component scanning can be enabled by component scanning tag in applicationContext.xml file.

<context:component-scan package="com.learning.spring" />

Adding this line in applicationContext.xml file will allow spring to scan all the java classes and look for the java class with the annotation @Component in turn which will create Bean that we can use in our project.

2. Add @Component annotation to the Java Class

So, in the previous step we enable component scanning in our applicationContext.xml file. Now we have to tell spring to register class to the bean. To do that we need to add @Component annotation to our java class.

@Component("theDog") //

This will tell spring to create a bean in where they will find a tag with the @Component annotation. Take a look at the example below :-

Dog.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.learning.spring;
 
import org.springframework.stereotype.Component;
 
@Component("theDog")
public class Dog {
 
    public Dog() {}
 
    public void animalSpeaks() {
        System.out.println("Dog Barks");
    }
}

Now we can use it in our java class

Main.java
Java
1
2
3
4
5
6
7
8
public class Main {
    public static void main(String[] args) {
 
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Dog dog = context.getBean("theDog", Dog.class);
        dog.animalSpeaks();
    }
}

3. Bean Scope

Let’s take a little time about learning about bean scopes. There are 5 types of bean scopes.

  1. Singleton Scope
  2. Prototype Scope – @Scope("prototype")
  3. RequestScope – @RequestScope
  4. SessionScope – @SessionScope
  5. ApplicationScope – @ApplicationScope
  6. WebsocketScope – @Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)

There are many usages of this scopes but we will talk about 2 scopes which are mostly important.

1. Singleton Scope

Singleton scope is the default scope that spring assigns the object at runtime. The singleton scopes shares the same reference to the variable when its created. Let’s say if you call the same object twice it will refer to same memory location and upon fetching the data it will retrieve same results.

You don’t havae to put any annotations while creating a bean with a singleton scope.

2. Prototype Scope

When we add @Prototype to any java class it tells spring framework to create new instance of object everytime it is received from the spring container. That means each object points to different memory location and the values that is set within the object are always different.

Dog.java
Java
1
2
3
4
@Scope("prototype")
public class Dog {
...
}

4. Depedency Injection Using @Autowired Annotation

There are 3 ways of injecting depedencies in spring application using autowired annotation. First we will see how to do it in constructor and then to other type of dependency injection methods.

1. Constructor Injection

To use constructor injection we need to add @Autowired annotation in our Java class. Make sure to keep the @Component annotation to the class which is injecting and being injected. Otherwise it will throw error saying cannot find the bean type of the class. Take a look at the example below :-

Dog.java
Java
1
2
3
4
5
6
7
8
9
10
@Component("theDog")
public class Dog {
 
    private final AnimalService animalService;
    
    @Autowired
    public Dog(AnimalService theAnimalService) {
        animalService = theAnimalService;
    }
}

2. Setter Injection

Setter injection is very similar to constructor injection. We just have to add @Autowired extension to the setter method. Take a look at the example below to check its use case.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
@Component("theDog")
public class Dog {
 
    private AnimalService animalService;
 
    public Dog() {
    }
 
    @Autowired
    public void setAnimalService(AnimalService theAnimalService) {
        this.animalService = theAnimalService;
    }
}

3. Field Injection

It is the most popular dependency injection method and widely used through out the projects by many developers. Its not the case that you should use only certain type of injection method. Just make sure to follow one approach accross all the project to maintain the consistency of the project.

Field injection are done directly to the fields without having to add the setter methods to the property and fields. It is mostly practiced by developers because you dont have to add it to the setter methods. Checkout the use case below :-

Dog.java
Java
1
2
3
4
5
6
7
8
9
@Component("theDog")
public class Dog {
    
    @Autowired
    private AnimalService animalService;
 
    public Dog() {
    }
}

5. Injecting Literal Values / By Using Properties File

To inject the literal values we can directly assignment to the fields. We just have to @Value annotation and give the value to the field.

Java.class
Java
1
2
3
4
5
6
7
8
9
@Component("theDog")
public class Dog {
 
    @Value("Tom")
    public String name;
    
    @Value("Lives on Land")
    public String habitat;
}

So, this is injecting values directly into the field. Sometime you have to inject the values directly from the properties file. To do that we need to register our application.properties file in applicationContext.xml.

<context:property-placeholder location="classpath:application.properties"/> 

Java
1
2
3
4
5
@Value("${animal.name}")
public String name;
 
@Value("${animal.habitat}")
public String habitat;

So, These are some of the most important annotations that you will be using while doing project with spring framework.

SHARE ON
Buffer

Enjoyed this article?

Like us on

JAVA

Avatar for SNK

About SNK

Hello Welcome to my Blog. I develop Websites Using Laravel Framwork & WordPress. Get Latest updates on Facebook | Twitter

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Get Connected !! With Us

TOP POSTS

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

TUTORIALS TILL DATE

  • September 2022 (6)
  • June 2021 (7)
  • October 2020 (5)
  • September 2020 (6)
  • September 2018 (14)
  • August 2018 (3)
  • July 2018 (4)
  • March 2018 (8)
  • February 2018 (5)
  • January 2018 (1)
  • December 2017 (2)
  • August 2017 (8)
  • May 2017 (1)
  • April 2017 (1)
  • March 2017 (4)
  • February 2017 (3)
  • January 2017 (4)

CATEGORIES

  • Angular (2)
  • CSS3 (3)
  • D3 (3)
  • HTML5 (7)
  • JAVA (11)
  • Javascript (20)
  • jQuery (8)
  • Laravel (35)
  • Others (3)
  • PHP (11)
  • Spring (2)
  • WordPress (10)

Top Categories

  • Angular
  • CSS3
  • D3
  • HTML5
  • JAVA
  • Javascript
  • jQuery
  • Laravel
  • Others
  • PHP
  • Spring
  • WordPress

Get in Touch

DMCA.com Protection Status

Recent Articles

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

© 2012-22 CodeIn House.  •  All Rights Reserved.