Spring-注解自动注入

问题:@autowired 和 java自带的@resource 到底是怎么样的自动注解流程?

1.在xml文件中设置自动注入

<bean id="cat" class="com.chang.pojo.Cat"/>
<bean id="dog" class="com.chang.pojo.Dog"/>

当一个bean节点带有 autowire byName的属性时。
1. 将查找其类中所有的set方法名,例如setCat,获得将set去掉并且首字母小写的字符串,即cat。
2. 去spring容器中寻找是否有此字符串名称id的对象。
3. 如果有,就取出注入;如果没有,就报空指针异常。
<bean id="person" class="com.chang.pojo.Person" autowire="byName">
    <property name="name" value="Cyq"/>
</bean>

autowire="byType" : spring会识别此bean.xml文件中是否有bean的class与本类中的引用类型相同 若相同则自动注入
可能会出现的问题:有多个bean的class相同 此时使用autowire="byType" 会出错 
<bean id="person" class="com.chang.pojo.Person" autowire="byType">
    <property name="name" value="Cyq"/>
</bean>

2.使用注解@autowired 和@resource 和 @Qualifie 完成自动注入

 pojo实体类

public class Person {
    private String name;
    //@Autowired
    @Qualifier("cat123")
    @Resource
    private Cat cat;
    @Resource
    //@Autowired
    private Dog dog;

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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">


    <bean id="cat12" class="com.chang.pojo.Cat"/>
    <bean id="cat123" class="com.chang.pojo.Cat"/>
    <bean id="dog" class="com.chang.pojo.Dog"/>
    <bean id="person" class="com.chang.pojo.Person">
        <property name="name" value="Cyq"/>
    </bean>


    <context:annotation-config/>

</beans>

使用注解的需要的支持部分

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

</beans>

使用注解步骤:

   1.在xml文件中添加context内容和 “ <context:annotation-config/>” 对直接进行支持

   2.在属性上面添加@Autowired 、@Resource、@Qualifier

注解名词解释:

@Autowired 使用byname不满足时再使用byType

@Resource则是 先使用byType不满足时再使用byname

我们也可以直接使用 @Qualifier(xxx)来指定我们要自动注释的bena对象的id

  • 12
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值