xml+注解结合模式,xml⽂件依然存在,spring IOC容器的启动仍然从加载xml开始
那么哪些bean的定义写在xml中,哪些bean的定义使⽤注解
第三方jar中的bean定义在xml,⽐如德鲁伊数据库连接池
自己开发的bean定义使⽤注解
xml中标签与注解的对应(IOC)
DI 依赖注⼊的注解实现方式(管理bean之间的依赖关系)
@Autowired(推荐使⽤):采取的策略为按照类型注⼊。
/*这样装配会去spring容器中找到类型为AccountDao的类,然后将其注⼊进来。这样会产⽣⼀个问题,
当⼀个类型有多个bean值的时候,会造成⽆法选择具体注⼊哪⼀个的情况,这个时候我们需要配合着@Qualifier使⽤。*/
@Service("transferService")
public class TransferServiceImpl {
@Autowired
private AccountDao accountDao;
}
@Qualifier告诉Spring具体去装配哪个对象。
//这个时候我们就可以通过类型和名称定位到我们想注⼊的对象
@Service("transferService")
public class TransferServiceImpl implements TransferService {
//@Autowired 按照类型注入 ,如果按照类型无法唯一锁定对象,可以结合@Qualifier指定具体的id
@Autowired
@Qualifier(name="jdbcAccountDaoImpl")
private AccountDao accountDao;
}
那么以前的applicationContext.xml中的bean配置现在完全可以移除,使用注解来替代了
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--开启注解扫描,base-package指定扫描的包路径-->
<context:component-scan base-package="com.tong"/>
<!--引入外部资源文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--第三方jar中的bean定义在xml中-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>
erty name="password" value="${jdbc.password}"/>
</bean>
</beans>