公众号:架构师与哈苏
关注公众号进入it交流群! 公众号:架构师与哈苏 不定时都会推送一些实用的干货。。。

@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();
    }

}

posted on 2020-09-18 10:46  公众号/架构师与哈苏  阅读(179)  评论(0)    收藏  举报