Home  >  Spring Core

Example of @Bean in Spring

By Arvind Rai, March 11, 2013
In spring @Bean is used to create a bean. The bean which we create in XML can also be created without XML. This approach is easier and more understandable. Find the complete example to use @Bean.

XMLFreeBeanTestConfig.java
 package com.concretepage;

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

@Configuration
public class XMLFreeBeanTestConfig {

	@Bean
    public City getCity() {
		City city= new City();
		city.setCityName("Varanasi");
		city.setArea(500);
        return city;
    }
	
	@Bean
	public Student getStudent(){
		Student student=new Student();
		student.setCity(getCity());
		return student;
	}
}
 


City.java
package com.concretepage;

public class City {
	private String cityName;
	private int area;

	public String getCityName() {
		return cityName;
	}

	public void setCityName(String cityName) {
		this.cityName = cityName;
	}

	public int getArea() {
		return area;
	}

	public void setArea(int area) {
		this.area = area;
	}

}
 


Student.java
package com.concretepage;

public class Student {
	private City city;
	
	public City getCity() {
		return city;
	}
	public void setCity(City city) {
		this.city = city;
	}
	    
}
 


XMLFreeBeanTest.java
package com.concretepage;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class XMLFreeBeanTest {
	
   public static void main(String[] args) {
	   AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	   
       ctx.register(XMLFreeBeanTestConfig.class);
       ctx.refresh();

       Student student = ctx.getBean(Student.class);
       System.out.println(student.getCity().getCityName());
       System.out.println(student.getCity().getArea());
               
   }

} 
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us