@Qualifier注解作用

@Qualifier 注解作用就是为了给Bean打上一个标记,用来查找bean,代码示例:

@Qualifier注解作用_第1张图片

  1. 创建一个java bean
package com.gupaoedu.springcloud.example.demo;

public class TestClass {
     
    private String name; // getter setter 略
}
  1. 编写配置类,将这个bean装载到IOC容器
package com.gupaoedu.springcloud.example.demo;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestConfiguration {
     

    @Bean("testClass1")
    TestClass testClass1(){
     
        return new TestClass("TestClass1");
    }
    @Qualifier
    @Bean("testClass2")
    TestClass testClass2(){
     
        return new TestClass("TestClass2");
    }
}
  1. 启动类,配置扫描包
package com.gupaoedu.springcloud.example.springclouduserservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "com.gupaoedu")
@SpringBootApplication
public class SpringCloudUserServiceApplication {
     
    public static void main(String[] args) {
     
        SpringApplication.run(SpringCloudUserServiceApplication.class, args);
    }
}
  1. 测试controller 对testClassList 加上@Qualifier注解
package com.gupaoedu.springcloud.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
@RestController
public class TestController {
     

    @Qualifier
    @Autowired
    List<TestClass> testClassList= Collections.emptyList();

    @GetMapping("/test")
    public Object test(){
     
        return testClassList;
    }

}

然后启动,访问/test, 看到只打印了 TestClass2
@Qualifier注解作用_第2张图片
然后对testClass1 Bean的注入,也加上@Qualifier注解后再请求/test

@Qualifier
@Bean("testClass1")
    TestClass testClass1(){
     
        return new TestClass("TestClass1");
    }

结果如下,可以看到,只有加了@Qualifier标记的Bean, 才会被注入给同样加了@Qualifier标记的 testClassList 这个list中
@Qualifier注解作用_第3张图片
注: 本文是为了给ribbon负载均衡原理中, @LoadBalanced注解实现负载均衡的原理做铺垫;

你可能感兴趣的:(springCloud源码学习,1024程序员节)