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

标签 java spring junit junit4

在我们的软件中,我们使用 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/

相关文章:

java - java中数组和二维数组相乘

java - Spring、JPA、Hibernate 3 vs 4

java - 使用拖放在 Spring 中创建表单?

java - Spring的TestNG回滚事务不起作用

java - Mockito 的@After 和 verifyNoMoreInteractions

java - 使用随机 int 的 ArrayIndexOutOfBoundsException

java - 在不同的包中为同一类使用两个 CDI 生成器 (Intellij)

java - Java 中的返回方法出现乱序

java - 从测试中获取 JUNIT 结果以将其结果发布到 testrail

java - JUnit:同时运行测试