SpringIOC应用之XML+注解模式

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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值