使用注解注入属性

本文介绍了在Spring框架中如何使用@Autowired和@Qualifier注解进行依赖注入。当@Autowired不能满足复杂的注入需求时,可以结合@Qualifier指定特定的bean进行注入。示例代码展示了在一个People类中,通过@Autowired和@Qualifier注解注入Dog和Cat类型的属性。
摘要由CSDN通过智能技术生成

使用注解注入属性

@Autowired与@Qualifier

1. 1. 1. 将@Autowired加在实体类的属性上面,可以自动通过属性名或属性类型来自动装配;
2. 2. 2. 如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解@Autowired完成的时候,我们可以使用@Qualifier(value = “xxx”)去配置@Autowired的使用,指定一个唯一的bean对象注入;
3. 3. 3. 使用@Autowired后就不需要set方法了。

package com.tl.pojo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 * @author tl
 */
public class People {
    private String name;
    @Autowired
    @Qualifier(value = "dog22")
    private Dog dog;
    @Autowired
    private Cat cat;

    public People() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Dog getDog() {
        return dog;
    }


    public Cat getCat() {
        return cat;
    }

}

配置

<?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/>
    <bean id="cat11" class="com.tl.pojo.Cat"/>
    <bean id="dog22" class="com.tl.pojo.Dog"/>
    <bean id="dog23" class="com.tl.pojo.Dog"/>
    <bean id="people" class="com.tl.pojo.People">
        <property name="name" value="tl"/>
<!--        <property name="cat" ref="cat"/>-->
<!--        <property name="dog" ref="dog"/>-->
    </bean>
</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值