Searching...
Tuesday, 13 August 2013

Spring Annotation based Bean configuration Example (@Bean)

01:11

In spring we can use @Bean annotations to create Bean. Here is one example which is using @Configuration and @Bean to create Beans without any xml configuration.

Software Used

Java 1.7
Spring 3 jars
Apache Common logging jars
Cglib2 jars

Create a bean class (Student.java)

package com.pretech; 
public class Student {
	privateString name;
	privateString address; 
	publicString getName() {
		returnname;
	} 
	publicvoidsetName(String name) {
		this.name= name;
	} 
	publicString getAddress() {
		returnaddress;
	} 
	publicvoidsetAddress(String address) {
		this.address= address;
	} 
}

Create a Bean configuration class

package com.pretech; 
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration; 
@Configuration
public class BeanConfig {
	@Bean
	publicStudent getStudentBean() {
		Student s = newStudent();
		s.setName("Vinod");
		s.setAddress("Bangalore");
		returns;
	}
}

Create a main class to test bean

package com.pretech; 
importorg.springframework.context.annotation.AnnotationConfigApplicationContext; 
public class Main { 
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = newAnnotationConfigApplicationContext();
		context.register(BeanConfig.class);
		context.refresh();
		Student student = context.getBean(Student.class);
		System.out.println(student.getName());
		System.out.println(student.getAddress());
	} 
}

Output



Vinod


Bangalore

0 comments: