读书人

利用Annotation回实现属性的注入

发布时间: 2012-09-05 15:19:34 作者: rapoo

利用Annotation来实现属性的注入

在以前的SPRING中我们通常采用的方式是在XML文件来来实现手动装配类的属性从而来实现IOC。

例如

<bean id="personDao" />
??</property>

</beam>

?

如果采用这种方式来进行装配,导致会是该XML十分的庞大和臃肿,在2.5中,可以采用@Resource的方式来进行自动装配。他的原理是首先来查找跟你标记属性名到XML文件中来找名字相同的,如果名字没有相同的再找类型相同的。

首先要做的工作:

1.加入Annotation所需要的命名空间(红色标记的)

<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:context="http://www.springframework.org/schema/context"
?xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
?http://www.springframework.org/schema/context
?http://www.springframework.org/schema/context/spring-context-2.5.xsd
?http://www.springframework.org/schema/aop
?http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
?<context:annotation-config/>

2.在你的所需奥装配的类的属性上或是set 方法上加入@Resource标签

?

package com.service;

import javax.annotation.Resource;

import com.dao.IPersonDao;

public class PersonService implements IPersonService {

?@Resource(name="personDao")
?public IPersonDao personDao;
?public IPersonDao getPersonDao() {
??return personDao;
?}

//或者在set方法上标记也可以
?public void setPersonDao(IPersonDao personDao) {
??this.personDao = personDao;
?}
?public void getPerson() {
??this.personDao.getPerson();

?}

}

?

然后在配置文件中直接写:

<bean id="personDao" class="com.service.PersonService">

??</beam>

?

就可以了。

?他的原理跟.net中attribute的原理是类似的。

读书人网 >软件架构设计

热点推荐