深入探索spring技术内幕(四): 剖析@Resource注解实现原理与注解注入(三)

2014-11-23 21:44:00 · 作者: · 浏览: 20
ss PersonServiceImplTest { @Test public void testSave() { ClassPathXMLApplicationContext ctx = new ClassPathXMLApplicationContext("beans.xml"); PersonService personService = (PersonService)ctx.getBean("personService"); personService.save(); } }

二、spring注解注入

① 引入common-annotations.jar

② 在xml中做如下配置:

  

  
	
   

  

③ 在Java代码中使用@Autowired或@Resource注解方式进行装配

二者区别: @Autowired默认按类型装配, @Resource默认按名称装配, 当找不到与名称匹配的Bean才会按类型匹配.

@Resource // 配置在属性上
private PersonDao personDao;

@Resource(name="personDao") // 名称通过@Resource的name属性指定
private PersonDao personDao;

@Resource // 配置在setter方法上
public void setPersonDao(PersonDao personDao) {
	this.personDao = personDao; 
}


@Autowired注解是按类型装配依赖对象, 默认情况下它要求依赖对象必须存在,

如果允许null值, 可以设置required=false

如果想使用按名称装配, 可以结合@Qualifier注解一起使用

@Autowired @Qualifier("personDao")
private PersonDao personDao


三、spring自动扫描和管理Bean

前面的例子都是使用xml的bean定义来配置组件, 在一个稍大的项目中, 通常会有上百个组件, 如果这些组件都采用xml的bean定义来配置, 显然会增加配置文件的体积, 查找及维护起来也不太方便.


spring2.5为我们引入了组件自动扫描机制, 它可以在类路径下寻找标注了@Component、@Controller、@Service、@Reponsitory注解的类, 并把这些类纳入进spring容器中管理. 它的作用和在xml中使用bean节点配置组件是一样的.

① beans.xml

  

  
           
	
    
	
   

  
② PersonServiceImpl

@Service("personService") 
@Scope("singleton")
public class PersonServiceImpl implements PersonService {
	private PersonDao personDao;
	
	@Resource(name="personDao") 
	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}
	
	@PostConstruct
	public void init(){
		System.out.println("init..");
	}
	
	@PreDestroy
	public void destory(){
		System.out.println("destory..");
	}
	public void save() {
		personDao.save();
	}
}
@Controller通常用于标注控制层组件(如struts中的action);

@Service通常用于标注业务层组件;

@Repository通常用于标注数据访问组件, 即DAO组件;

@Component泛指组件, 当组件不好归类的时候, 我们可以使用这个注解进行标注;