step1:配置文件中添加说明:
<context:annotation-config/> 宣告要用注解方式进行配置
<bean name="c" class="com.how2java.pojo.Category"
step2:通过@Autowired实现自动装配:
在成员变量上:
@Autowired
private Category category;
或在setter上:
@Autowired
public void setCategory(Category category) {
this.category = category;
}
通过context.getBean("p")获得对象Product后,在进行Product的getCategory方法时,扫描到Category/Setter前的@Autowired 标签,之后将搜索配置文件中对应的bean,实现自动装配。
或通过@Resource来进行标注: @Resource(name="c")
private Category category;
对Product中属性Category,注入bean:"c":Category。
step3:对bean进行注解配置:
配置文件为:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" 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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.how2java.pojo"/> 将bean的配置全部移到定义类中进行;
</beans>
在定义类Product中:
package com.how2java.pojo;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component("p") //定义bean:Product的关键字为"p";
public class Product {
private int id;
private String name="product 1";
@Autowired //自动注入对象Category;
private Category category;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
在定义类Category中:
@Component("c") //bean:Category的关键字为"c";
public class Category {
step4:注解方式测试:
注解方法实现的测试类:
package com.how2java.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.how2java.pojo.Category;
@RunWith(SpringJUnit4ClassRunner.class) //表明这是Spring的测试类;
@ContextConfiguration("classpath:applicationContext.xml") //表明配置文件的位置;
public class TestSpring {
@Autowired //自动装配对象Category;
Category c;
@Test //进行测试;
public void test(){
System.out.println(c.getName());
}
}