Spring使用注解实现自动配装

在beans.xml中配置(配置注解的支持)

原先的基本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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    </bean>
</beans>

添加相应的context配置

<?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.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">
   
    <!--开启注解的支持有了自动配装,可以不需要set方法-->
    <context:annotation-config/>
</beans>

两类注解

  • Autowired:默认按类型装配,使用Autowired我们就可以不用编写set方法了,前提是你这个自动配置的属性在IOC(Spring)容器中存在,且符合名字ByType!

  • Qualifier:与Autowired配套使用,作为修饰,如果当Spring上下文中存在不止一个UserDao类型的bean时,可以使用Qualifier来指定某个实例

 beans.xml中声明类对象

    <bean id="cat1" class="com.cat.pojo.Cat"/>
    <bean id="cat2" class="com.cat.pojo.Cat"/>
    <bean id="dog1" class="com.cat.pojo.Dog"/>
    <bean id="dog2" class="com.cat.pojo.Dog"/>
    <bean id="people" class="com.cat.pojo.People"/>

使用Autowired注解

public class People {

    @Autowired
    @Qualifier(value ="cat1" )
    private Cat cat;
    
    @Autowired
    @Qualifier(value ="dog2" )
    private Dog dog;
    
}

使用Resource注解

public class People {
    @Resource(name = "cat1")
    private Cat cat;

    @Resource(name = "dog2")
    private Dog dog;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值