您的位置:首页 > 编程语言 > Java开发

spring注入方式之AutoWired注入

2013-08-22 23:59 351 查看
注解方式有两种(注解在变量上和注解在方法上)
DAO
public class PersonDao {
public void add(){
System.out.println("dao的add方法");
}
}

1.Service(注解在变量上)
public class Service {

/*
* @Autowired注解
*   * 默认按类型注入,如果类型不匹配抛出异常
*   * 该注解能应用到字段上和属性的set方法上(两种方式)
*
*   当该注解应用到字段上(spring容器已经初始化)
*      * 注解解析器获取@Autowired注解标注(private PersonDao personDao;)的变量的类型.看类型是com.xxc.iocc.autoWiredField.dao.PersonDao
*
*      * 以该类型为查找条件到spring容器中去查找类型为com.xxc.iocc.autoWiredField.dao.PersonDao的bean节点
*              <bean id="personDao" class="com.xxc.iocc.autoWiredField.dao.PersonDao"></bean>
*
*      * 反射该节点的,并将实例赋给 private PersonDao personDao变量
*
*      * @Autowired配合 @Qualifier("personDao") 可以按bean的id属性匹配来进行注入,@Qualifier不能单独使用
*/

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

public void add(){
System.out.println("service的add方法");
personDao.add();
}
}



2.Service注解在方法上
public class Service {

private PersonDao personDao;

public PersonDao getPersonDao() {
return personDao;
}

/*
* @Autowired注解
*   * 默认按类型注入,如果类型不匹配抛出异常
*   * 该注解能应用到字段上和属性的set方法上(两种方式)
*
*   当该注解应用到方法上(spring容器已经初始化)
*      * 注解解析器获取@Autowired注解setPersonDao(PersonDao personDao),获取方法的参数类型
*
*      * 以该参数类型为查找条件到spring容器中去查找类型为com.xxc.iocc.autoWiredMethod.dao.PersonDao的bean节点
*              <bean id="personDao" class="com.xxc.iocc.autoWiredMethod.dao.PersonDao"></bean>
*
*      * 以bean节点的类型的实例对象作为实参传递给setPersonDao(PersonDao personDao)的形参进行注入
*
*      * @Qualifier("personDao") 可以使用该标记按名称匹配,但是位置要放在形参前面
*/
@Autowired
public void setPersonDao(@Qualifier("personDao22")PersonDao personDao) {
this.personDao = personDao;
}

public void add(){
System.out.println("service的add方法");
personDao.add();
}
}


applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <!-- 使用基于注解的进行注入步骤如下
* 引入context命名空间
xmlns:context="http://www.springframework.org/schema/context" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd

* 注册对注解进行解析的处理器
context:annotation-config

-->

<context:annotation-config/>

<bean id="service" class="com.xxc.iocc.autoWiredField.service.Service"/>
<bean id="personDao22" class="com.xxc.iocc.autoWiredField.dao.PersonDao"/>
</beans>


测试类
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("com/xxc/iocc/autoWiredField/applicationContext.xml");
Service service = (Service)ac.getBean("service");
service.add();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: