1,新建一java工程:springJavaTest。
2,加入spring2.5的包(2.5版本才能用注释注入)
3,新建两个javaBean:Room.java 和 House.java,如下:
package com.bean; public class Room { private String area = "100平米"; //动作 public String say(){ return "my area is " +area; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } }
package com.bean; import org.springframework.beans.factory.annotation.Autowired; public class House { @Autowired private Room room; @Override public String toString() { return room.say(); } }
4, 修改配置文件applicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- 该 BeanPostProcessor 将自动起作用,对标注 @Autowired 的 Bean 进行自动注入 --> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <bean id="room" class="com.bean.Room"> <property name="area" value="860平方米"/> </bean> <bean id="house" class="com.bean.House"> </bean> </beans>
5,新建测试类SpringTest.java
package com.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.bean.House; public class SpringTest { public static void main(String[] args) { String[] locations = {"applicationContext.xml"}; ApplicationContext context = new ClassPathXmlApplicationContext(locations); House house = (House) context.getBean("house"); System.out.println(house); } }