Home  >  Spring Core

Example of @Configuration in Spring

By Arvind Rai, March 11, 2013
In spring @Configuration can be used for XML free coding. @Configuration belongs to the package org.springframework.context.annotation. @Configuration is annotation based. Find the code snippet for how to use @Configuration.

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;
	}
}
 
@Bean is used to create bean. The above code is equivalent to below XML code.
<bean id="city" class="com.concretepage.City">
   <property name="cityName" value="Varanasi"/>
   <property name="area" value="500"/>
</bean>

<bean id="student" class="com.concretepage. Student ">
   <property name="city">
	  <ref bean=" city" />
   </property>
 </bean>

 


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