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 ?
- Add Component Scanning in XML.
- Add @Component annotation to the Java class
- Bean Scope.
- Depedency Injection using @Autowired Annotation.
- 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 :-
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
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.
- Singleton Scope
- Prototype Scope –
@Scope("prototype")
- RequestScope –
@RequestScope
- SessionScope –
@SessionScope
- ApplicationScope –
@ApplicationScope
- 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.
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 :-
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 @Autowire
d extension to the setter method. Take a look at the example below to check its use case.
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 :-
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.
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"/>
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.
Leave a Reply