java—如何通过方法创建具有相同类的两个bean?

ht4b089n  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(826)

我想创建clazz,在这里我可以创建两个具有相同类但配置不同的bean。

public class Clazz {
//same class : Client, inside has the different configuration
//inicilized by methods
@Bean(name="Bean1")
public Client1 (){}

@Bean(name = "Bean2")
public Clien2t (){}
}

然后我想把它们注入其他类中

public class ClassForInjectBean1{

@Autowired
@Qualifier("Bean1")
@NotNull 
Client client
....
}

public class ClassForInjectBean2{

@Autowired
@Qualifier("Bean2")
@NotNull 
Client client
....
}

我在类forinjectbean1和类forinjectbean2中尝试过这种构造

@Resource(name = "Bean2")
@NotNull 
Client client

@Autowired
@Qualifier("Bean2")

但Spring不明白
ошибка : classforinjectbean1中构造函数的参数1需要单个bean,但找到了2:-bean1:由类路径资源中的方法“client1”定义…-bean2:由类路径资源中的方法“client2”定义。。。为什么我不能这么做?
我知道有一条路https://www.baeldung.com/spring-qualifier-annotation,但我不需要创建许多类和接口。

wnrlj8wa

wnrlj8wa1#

尝试使用 @Configuration .
指示一个类声明一个或多个@bean方法,并可由spring容器处理,以便在运行时为这些bean生成bean定义和服务请求
我给你举了一些例子。

@Configuration
public class Cfg {

    @Bean("client1")
    public Client client1() {
        return new Client("client1");
    }

    @Bean("client2")
    public Client client2() {
        return new Client("client2");
    }
}
public class Client {
    private String name;

    public Client(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Client{" +
                "name='" + name + '\'' +
                '}';
    }
}
@Component
public class InjectionTest {

    @Component
    public class ClassForInjectBean1 {
        private final Client client;

        public ClassForInjectBean1(@Qualifier("client1") Client client) {
            this.client = client;
        }

        @PostConstruct
        public void testInit() {
            System.out.println(client.toString());
        }
    }

    @Component
    public class ClassForInjectBean2 {
        private final Client client;

        public ClassForInjectBean2(@Qualifier("client2") Client client) {
            this.client = client;
        }

        @PostConstruct
        public void testInit() {
            System.out.println(client.toString());
        }
    }
}

输出为:

Client{name='client2'}
Client{name='client1'}

相关问题