依赖注入@Autowired@Primary@Quelifier使用

@Autowired

注入声明的SpringBean对象,根据一定的规则首先按照注入的类型去查找,如果没有找到安装注入的名称去匹配你要注入的属性名称,如果都没有找到启动项目时抛出异常,@Autowired(required = false) 表示没有找到注入对象时,不抛异常,注入null。

@Primary

如果有多个相同类型的SpringBean,我们可以使用@Primary注解,优先注入带该注解标识的类,@Primary可以在多个类上标注,那就会抛异常。

 

package com.wzq.dome.entity;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

/**
 * @description:
 * @author: Wzq
 * @create: 2019-12-12 10:52
 */
@Primary
@Component
public class UserStatic {

    public static String hello;

    @Value("${hello}")
    public void setHello(String hello){
        UserStatic.hello = hello;
    }

}

@Quelifier

使用SpringBean的名称(SpringBean的名称都是唯一的)进行注入。

 

package com.wzq.dome.action;

import com.wzq.dome.entity.ProFileEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description:
 * @author: Wzq
 * @create: 2019-12-12 10:27
 */
@RestController
public class TestController {



    @Autowired()
    @Qualifier(value = "proFileEntity")
    ProFileEntity proFileEntity;

    @RequestMapping("/test")
    public String test(){
        return proFileEntity.getName();
    }

}

个人微信公众,经常更新一些实用的干货:

 

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值