Spring Based Configuration – Java Annotation

spring-framework-spring-based-configuration-java-annotation-feature-image

Spring based configuration using Annotation help you to create Spring configurations without XML.
This tutorial give you an example with most of Spring Annotation for configuration: @Configuration, @Bean (with custom bean lifecycle method), @Import, @Scope. And they’re in multi-configuration context.

I. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE (It’s OK if you use Eclipse)

II. Overview
1. Project Structure

configuration-structure

2. Step to do

– Create Maven project
– Add Dependencies & Plugins
– Create Classes for Beans & Configuration Classes
– Create MainApplication Class
– Run Application & Enjoy Result

IV. Practice
1. Create Maven project

– Open Spring Tool Suite, on Menu, choose File -> New -> Maven Project.
– Check Create a simple project, choose Workspace Location and click Next.
– Fill all fields in Artifact group box, then click Finish.

2. Add Dependencies & Plugins

Open pom.xml, add:

	
		1.8
		4.3.2.RELEASE
	

	
		
			org.springframework
			spring-context
			${org.springframework-version}
		
	

	
		
			
				
					org.apache.maven.plugins
					maven-compiler-plugin
					3.3
					
						1.8
						1.8
					
				
			
		
	
3. Create Classes for Beans & Configuration Classes

CustomerService.java

package com.javasampleapproach.configuration;

public class CustomerService {
	private String name;

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return "This is: " + name;
	}
}

Location.java

package com.javasampleapproach.configuration;

public class Location {
	private String address = "Massachusetts";

	public Location() {
		System.out.println("Call constructor for Location");
	}

	public String getAddress() {
		return address;
	}
}

CustomerInfo.java

package com.javasampleapproach.configuration;

public class CustomerInfo {
	private Location location;

	public CustomerInfo(Location location) {
		System.out.println("Call constructor for CustomerInfo");
		this.location = location;
	}

	public String getInfo() {
		return "Location = " + location.getAddress();
	}
}

Under package config, create CustomerServiceConfig.java:

package com.javasampleapproach.configuration.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.javasampleapproach.configuration.CustomerInfo;
import com.javasampleapproach.configuration.CustomerService;
import com.javasampleapproach.configuration.Location;

@Configuration
public class CustomerServiceConfig {
	@Bean
	public CustomerService customerService() {
		return new CustomerService();
	}
	
	@Bean
	public CustomerInfo customerInfo(){
		return new CustomerInfo(location());
	}
	
	@Bean
	public Location location(){
		return new Location();
	}
}

@Configuration: indicates that a class will have @Bean methods and can be used by the Spring IoC container to generate bean definitions.
@Bean: the method which are annotated by @Bean will return an object that should be registered as a bean in Application Context.

Hence, above Java code will be equivalent to XML Configuration:

	

	

	
		
	

Now, we come to another @Configuration class with new Bean.
PaymentService.java

package com.javasampleapproach.configuration;

public class PaymentService {
	private String type = "online";

	public PaymentService() {
	}

	public void init() {
		System.out.println("Bean custom init method");
	}

	public void destroy() {
		System.out.println("Bean custom destroy method");
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}
}

Under package config, create AnotherCustomerServiceConfig.java:

package com.javasampleapproach.configuration.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Scope;

import com.javasampleapproach.configuration.PaymentService;

@Configuration
@Import(CustomerServiceConfig.class)
public class AnotherCustomerServiceConfig {
	
	@Bean(initMethod = "init", destroyMethod = "destroy" )
	@Scope("singleton")
	public PaymentService paymentService(){
		return new PaymentService();
	}
}

@Import: loads @Bean definitions from another configuration class (CustomerServiceConfig). So when calling construct method for AnnotationConfigApplicationContext, we only need to push AnotherCustomerServiceConfig.class as input parameter, all Beans from CustomerServiceConfig will be gotten automatically.
@Scope and custom init/destroy method can be annotated to Bean without adding anything in XML Configuration.

4. Create MainApplication Class

Under package main, create MainApplication.java:

package com.javasampleapproach.configuration.main;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

import com.javasampleapproach.configuration.CustomerInfo;
import com.javasampleapproach.configuration.CustomerService;
import com.javasampleapproach.configuration.PaymentService;
import com.javasampleapproach.configuration.config.AnotherCustomerServiceConfig;
import com.javasampleapproach.configuration.config.CustomerServiceConfig;

public class MainApplication {
	public static void main(String[] args) {
		AbstractApplicationContext context = new AnnotationConfigApplicationContext(CustomerServiceConfig.class);
		
		CustomerService customerService = context.getBean(CustomerService.class);
		customerService.setName("Telephone Service");
		System.out.println(customerService.getName());

		System.out.println("-----");
		// Injecting Bean Dependencies
		CustomerInfo customerInfo = context.getBean(CustomerInfo.class);
		System.out.println("Customer Info: " + customerInfo.getInfo());

		context.close();
		System.out.println("-----");
		// @Import Annotation
		AbstractApplicationContext newContext = new AnnotationConfigApplicationContext(
				AnotherCustomerServiceConfig.class);
		CustomerService newCustomerService = newContext.getBean(CustomerService.class);
		newCustomerService.setName("Consultation Service");
		System.out.println(newCustomerService.getName());

		System.out.println("-----");
		// Bean Lifecycle Custom methods
		PaymentService paymentService = newContext.getBean(PaymentService.class);
		System.out.println("Payment: " + paymentService.getType());

		// Test Bean Scope
		paymentService.setType("cash");
		paymentService = newContext.getBean(PaymentService.class);
		System.out.println("Payment: " + paymentService.getType());

		newContext.close();
	}
}
5. Run Application & Enjoy Result

– Config maven build:
clean install
– Run project with mode Java Application
– Check results in Console Screen:

Call constructor for Location
Call constructor for CustomerInfo
This is: Telephone Service
-----
Customer Info: Location = Massachusetts
-----
Call constructor for Location
Call constructor for CustomerInfo
Bean custom init method
This is: Consultation Service
-----
Payment: online
Payment: cash
Bean custom destroy method
IV. Source Code

springconfiguration



By grokonez | September 16, 2016.

Last updated on September 23, 2018.



Related Posts


Got Something To Say:

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

*