Spring容器的依赖注入方式(二)
如果通过配置beans.xml的方式对属性进行注入,需要编写大量的xml代码,造成了配置文件的臃肿,为了解决这个问题,spring提供了在JAVA代码中通过注解的方式来对属性进行装配。
方法三:通过注解方式对属性进行注入
第一步:要使用注解方式进行装备,首先需要修改beans.xml文件,让spring打开注解功能:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<!-- 引入 context 命名空间 -->
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
<!-- 加入 context scheme文件 -->
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 打开注解功能 -->
<context:annotation-config/>
......
</beans>第二步:依然是将需要交给Spring管理的类配置到beans.xml文件中
<bean name="personDao" class="com.risetek.dao.impl.PersonDaoImpl"/> <bean name="personServiceBean" class="com.risetek.service.impl.PersonServiceBean"/>
第三步:在java类中为需要注入的属性加上注解
这里有两种注解可以使用:
1. @Resource 该注解是jdk1.5提供的一个注解类型,因此使用该注解不会使代码跟spring框架产生太大的耦合,建议在开发过程中使用该注解,该注解在默认装配过程中首先根据名称来进行装配,再根据类型进行装配
public class PersonServiceBean implements PersonService {
//1.name属性指定spring容器中管理的bean的名称(如果指定了name属性,则如果spring容器会只按照name属性指定的bean名称来进行装配
//2.如果不指定name属性,那么容器会首先会按照属性的名称在spring容器中查找bean类进行装配,如果找不到bean类则再按照属性的类型进行装配
@Resource(name="personDao")
private PersonDao personDao;
//用注解方式则不需要提供属性的set方法了
// public void setPersonDao(PersonDao personDao){
// this.personDao = personDao;
// }
} 也可以将注解用到set方法上
public class PersonServiceBean implements PersonService {
private PersonDao personDao;
@Resource(name="personDao")
public void setPersonDao(PersonDao personDao){
this.personDao = personDao;
}
}2. @Aotuwire 该注解是有spring提供的一个注解类型,默认情况下(不配置@Qualifier注解)它会按类型来装配属性
public class PersonServiceBean implements PersonService {
//如果指定了required值为true,则如果找不到合适的bean进行装配,则会抛出异常,如果值为false,则找不到bean装配会将属性值装配为null
@Autowired(required=true)
//不指定@Qualifier注解时,默认按照属性类型进行装配
//在指定了@Qualifier后,则只会按照@Qualifier指定的名称进行装配
@Qualifier("personDao")
private PersonDao personDao;
}同样也可以将注解写在set方法上
public class PersonServiceBean implements PersonService {
private PersonDao personDao;
@Autowired
@Qualifier("personDao")
public void setPersonDao(PersonDao personDao){
this.personDao = personDao;
}
} 相关推荐
与卿画眉共浮生 2020-10-14
xiyang 2020-08-21
baijinswpu 2020-07-29
leonranri 2020-07-26
zhongliwen 2020-07-05
麋鹿麋鹿迷了路 2020-07-05
zengyu00 2020-07-05
XGQ 2020-07-04
CoderBoy 2020-06-28
whbing 2020-06-28
绝望的乐园 2020-06-27
wellfly 2020-06-26
菇星獨行 2020-06-25
草原孤狼 2020-06-25
坚持着执着 2020-06-16
wcqwcq 2020-06-14
yuanye0 2020-06-14
zhongliwen 2020-06-13
MrFuWen 2020-06-09