gpt4 book ai didi

java - Spring java 配置扩展抽象配置

转载 作者:行者123 更新时间:2023-12-01 09:29:21 26 4
gpt4 key购买 nike

在我们的软件中,我们使用 spring java 配置。我们有一个设置,其中一个配置扩展了一个抽象配置。请看一下这个测试用例:

import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class SpringConfigTest {

@Test
public void test() {
final AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfig.class);
ctx.getBeansOfType(AtomicInteger.class).entrySet().stream().forEach(b -> System.out.println(b.getKey() + " : " + b.getValue() + " (" + b.getValue().hashCode() + ")"));
}

@Configuration
public static class MyConfig extends AbstractConfig {

@Bean(name = "anotherName")
public AtomicInteger myBean() {
return new AtomicInteger(5);
}
}

public static abstract class AbstractConfig {

@Bean
public AtomicInteger myBean() {
return new AtomicInteger(10);
}
}
}

这个想法是,MyConfig覆盖AbstractConfig并且在创建的ApplicationContext中只有一个类型为AtomicInteger的bean名字下anotherName .

结果是:

anotherName : 5 (2109798150)myBean : 5 (1074389766)

So it says, there are two beans (two instances - one for each name) - and even more surpring: the same method (MyConfig#myBean()) was used to create both of them.

This behaviour looks odd to us: We expected that spring would either respect the usual java way of inheritance and create only the bean from MyConfig... or at least would create two independent beans ("10" and "5") in case it sees AbstractConfig as an independant config.

While investigating this we also tried to register the method name on the MyConfig class:

public static class MyConfig extends AbstractConfig {

@Bean(name = ["anotherName", "myBean"])
public AtomicInteger myBean() {
...

这次我们只得到了一个 bean: anotherName : 5 (2109798150)

..让我们更惊讶的是。

有谁知道这是否真的是正确的行为,还是我们只是错误地使用它?我们应该在 spring 的 jira 中提票吗?提前致谢!

最佳答案

我不是 Spring 专业人士,但我想说这种行为是设计使然的。为了实现你想要的(我希望我猜对了)“注入(inject)这个bean而不是另一个”你可以使用 @Primary在 bean 上,根据情况选择性地启用配置,您可以使用 @Conditional@Profile .

关于java - Spring java 配置扩展抽象配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39573558/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com