通过代码与通过注释配置的Spring配置

问题描述 投票:0回答:1

我通过以下代码创建Spring ApplicationContext:

public static AnnotationConfigWebApplicationContext startContext(String activeProfile,
                              PropertySource<?> propertySource, Class<?>... configs) {
    AnnotationConfigWebApplicationContext result = new AnnotationConfigWebApplicationContext();
    if (propertySource != null) {
        result.getEnvironment().getPropertySources().addLast(propertySource);
    }
    if (activeProfile != null) {
        result.getEnvironment().setActiveProfiles(activeProfile);
    }
    result.register(configs);
    result.refresh();
    return result;
}

在测试类我称之为:

@RunWith(SpringJUnit4ClassRunner.class)
class FunctionalTest {
    private ApplicationContext appContext;

    @BeforeEach
    void init() {
        appContext = Utils.startContext("functionalTest", getPropertySource(), 
                            BaseConfig.class, MyApplication.class, StorageTestConfig.class);
    }
}

它工作正常,没有问题。

现在我试图通过注释做同样的事情:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {BaseConfig.class, MyApplication.class, StorageTestConfig.class}, 
                      loader = AnnotationConfigContextLoader.class)
@ActiveProfiles("functionalTest")
@PropertySource(value = "classpath:test-context.properties")
class FunctionalTest {
      @Autowired
      private ApplicationContext applicationContext;
      ...
}

这根本不起作用。 applicationContext不是自动装配的,来自配置的bean也是。你能告诉我可能我做错了吗?

为什么我要从代码切换到注释:我希望能够从配置中自动装配bean。现在(以上下文创建的代码方式)我应该在测试方法中编写类似appContext.getBean("jdbcTemplate", JdbcTemplate.class)的东西。如果我能写的话会很棒的

@Autowired
private JdbcTemplate jdbcTemplate;

这将工作:)

spring-annotations applicationcontext spring-bean spring-config springjunit4classrunner
1个回答
1
投票

看起来你正在同时使用两个版本的JUnit:JUnit 4和JUnit 5.(或者同时使用JUnit4 api和JUnit5 api)

注释@Test来自你的FunctionalTest

org.junit.Test?或者是org.junit.jupiter.api.Test

似乎它来自org.junit.jupiter.api.Test

然后你应该使用@ExtendWith(SpringExtension.class而不是@RunWith(SpringJUnit4ClassRunner.class)

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {BaseConfig.class, Utils.ServConfig.class, Utils.MvcConfig.class, MyApplication.class, StorageTestConfig.class}, 
                  loader = AnnotationConfigContextLoader.class)
@ActiveProfiles("functionalTest")
@PropertySource(value = "classpath:test-context.properties")
class FunctionalTest {
      @Autowired
      private ApplicationContext applicationContext;

}

请注意,自SpringExtension版本以来,5.0可用。如果您使用的是较低版本,则必须使用JUnit4,使用org.junit.Test标记测试方法

在测试类我称之为:它工作正常,没有问题。

@RunWith(SpringJUnit4ClassRunner.class)在这里毫无价值。您使用JUnit5运行此测试。 @RunWith没有考虑。但@BeforeEach被认为。因此它正在发挥作用。

在你的FunctionalTest没有注释,因此它不起作用。使用JUnit4(@org.junit.Test@RunWith)或JUnit5(@org.junit.jupiter.api.Test@ExtendWith)。

似乎您同时使用两个版本的JUnit:JUnit 4和JUnit 5。

如果您没有从JUnit4迁移到JUnit 5,请考虑仅使用一个版本的JUnit。

© www.soinside.com 2019 - 2024. All rights reserved.