In this example we will observe how to use @Configuration and @Bean spring annotations.

  • @Configuration – Source of Bean definitions
  • @Bean – Defined on method to indicate the returned bean to be managed by Spring Container.

1. Spring XML based configuration

  <bean name="adminBean" class="com.codesimplify.Administrator">
       <property name="firstName" value="john" />
       <property name="lastName" value="smith" />
  </bean>

Full Example can be found at Simple Spring Bean Example

2. Example with Spring JavaConfig

package com.codesimplify;

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

@Configuration
public class AppConfig {

	@Bean
	public Administrator adminBean(){
		Administrator admin=new Administrator();
		admin.setFirstName("john");
		admin.setLastName("smith");
		return admin;
	}
	
}

In the above example, AppConfig acts as a configuration class and it defines multiple beans. Each bean definition consist of a method that should have public access modifier and should return the bean type and name of the method will become name of the bean.

3. Example Application class that validates above behavior

package com.codesimplify;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class App {

	public static void main(String[] args) {
		
		AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(AppConfig.class);
		Administrator adminBean=(Administrator)context.getBean("adminBean");
		System.out.println(adminBean);
	}
}

Spring class AnnotationConfigApplicationContext will be used to load configuration class AppConfig

Output:

FirstName: john , LastName: smith
Spring Bean – JavaConfig Example

2 thoughts on “Spring Bean – JavaConfig Example

Leave a Reply

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