Home  >  Spring Core

Annotation Based Configuration in Spring

By Arvind Rai, August 06, 2013
Spring <context:annotation-config/> tag looks for annotations on beans. If we want to use beans which has annotations for some purpose, then <context:annotation-config/> should be used. In case of Web Applications, it only checks @Autowired beans. We are showing the example in which bean is using an annotation i.e @Resource.
spring-app.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
 <context:annotation-config  />
<bean id="student" class="com.concretepage.Student">
</bean>
<bean id="add" class="com.concretepage.City">
	<property name="cityName" value="varanasi"/>
</bean>
</beans> 




City.java
package com.concretepage;
public class City {
	private String cityName;
	public String getCityName() {
		return cityName;
	}
	public void setCityName(String cityName) {
		this.cityName = cityName;
	}
} 
Student.java
package com.concretepage;
import javax.annotation.Resource;
public class Student {
	@Resource(name="add")
	private City city;

	public City getCity() {
		return city;
	}
	public void setCity(City city) {
		this.city = city;
	}
} 
SpringDemo.java
package com.concretepage;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDemo {
    public static void main(String... args) {
    	AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-app.xml");
            Student st=(Student) context.getBean("student");
            String city=st.getCity().getCityName();
            System.out.println(city);
    } 
} 

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us