Web.xml的配置、PersonDao类、PersonService类、PersonDaoBean类、与1中相同。使用注解方法进行依赖装配需要添加
common-annotations.jar包。
1)beans.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" 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">
<context:annotation-config /> <!-- 使用@Resource注解注入的添加项 -->
<bean id="personDao" class="springDaoBean.PersonDaoBean" />
<bean id="personDaoxxx" class="springDaoBean.PersonDaoBean" />
<bean id="personService" class="springDaoBean.PersonServiceBean" />
</beans>
2)PersonServiceBean类的代码:
public class PersonServiceBean implements PersonService {
// ==================@Resource注解注入方法===============
// @Resource注解注入方法执行原理:(按名称装配)
// 1)@Resource 执行时会默认按名称装配,添加在字段上则以字段名为bean在xml文件中进行依赖装配,
// 添加在setter方法上则默认以属性名为bean名在xml文件中进行依赖装配;
// 若不存在,则按类型依赖装配,最终装配不到时会报错;
// 2)@Resource(name="beanName") 执行时只会按名称在xml文件中进行依赖装配,若不存在,则报错;
// 第一种注解注入方法:在字段前添加@Resource
@Resource
private PersonDao personDao;
// 第二种注解注入方法:在字段前添加@Resource(name="在xml文件中要注入bean的名称")
// @Resource(name = "personDaoxxx")
// private PersonDao personDao;
// 第三种注解注入方法:在属性的setter方法前添加@Resource
// @Resource
// public void setPersonDao(PersonDao personDao) {
// this.personDao = personDao;
// }
// 第四种注解注入方法:在属性的setter方法前添加@Resource(name="在xml文件中要注入bean的名称")
// @Resource(name = "personDaoxxx")
// public void setPersonDao(PersonDao personDao) {
// this.personDao = personDao;
// }
// ===============@Autowired注解注入方法====================
// @Autowired注解注入原理:(按类型装配,若同时存在多个相同类型的bean,则报错)
// 1)@Autowired添加在字段上或添加在setter方法上,自动按字段的类型和属性的类型依赖装配;
// 依赖装配不到的话,则报错;
// 2)@Autowired @Qulifier(value="在xml文件中要注入bean的名称")
// 执行时只会按名称在xml文件中进行依赖装配,若不存在,则报错;
// 第一种注解注入方法
// @Autowired
// private PersonDao personDao;
// 第二种注解注入方法
// @Autowired @Qualifier(value = "personDaoxxx")
// private PersonDao personDao;
// 第三种注解注入方法
// @Autowired
// public void setPersonDao(PersonDao personDao) {
// this.personDao = personDao;
// }
public void save() {
personDao.add();
}
}
3)springTest类的代码:
public class springTest {
@Test
public void instanceSpring() {
AbstractApplicationContext ctx = new
ClassPathXmlApplicationContext("springXml/beans.xml");
PersonService personService = (PersonService)
ctx.getBean("personService");
personService.save();
}
}