Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用现有的应用程序';什么是spring配置类?_Java_Spring_Spring 4 - Fatal编程技术网

Java 如何使用现有的应用程序';什么是spring配置类?

Java 如何使用现有的应用程序';什么是spring配置类?,java,spring,spring-4,Java,Spring,Spring 4,在我的代码中,我不想加载XXApplicationConfig类中定义的所有bean XXApplicationConfig是一个@Configuration注释文件,它定义了大量Springbeans 所以,我想在测试时只从XXApplicationConfig类加载AppBean,以减少加载测试时间,并区分我正在测试的内容。我还想使用XXApplicationConfig类加载该类,以确保定义的bean配置也正确 这是我的测试类(已修改),用于测试AppBean类 你能告诉我这是否是正确的方

在我的代码中,我不想加载XXApplicationConfig类中定义的所有bean

XXApplicationConfig是一个@Configuration注释文件,它定义了大量Springbeans

所以,我想在测试时只从XXApplicationConfig类加载AppBean,以减少加载测试时间,并区分我正在测试的内容。我还想使用XXApplicationConfig类加载该类,以确保定义的bean配置也正确

这是我的测试类(已修改),用于测试AppBean类

你能告诉我这是否是正确的方法,并建议如何使它更好吗?目前,这种方法似乎正在发挥作用。但是,不确定这是否是正确的方法

@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class ApplicationTest {

    @Configuration
    @PropertySources(value = {@PropertySource("classpath:test.properties")})
    static class MyTestConfiguration {

        @Bean
        public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceHolderConfigurer()  {
            return new PropertySourcesPlaceholderConfigurer();
        }

        @Bean
        public XXApplicationConfig xxAppConfig() {
            return new XXApplicationConfig();
        }

        @Bean
        public CustomTestService customTestService() {
            return new CustomTestService();
        }

        @Bean
        public AppBean appBean() throws Exception {
            return XXApplicationConfig().appBean();
        }

    }

    @Autowired
    private AppBean appBean;


    @Test
    public void testAppBean() {
        test appBean.doSomething();
    }
}

如果只想测试一个对象,只需使用该类的构造函数创建该类的一个对象。春豆被设计成pojo。Spring上下文只是创建和连接对象的一种方便方式。没有什么可以阻止您自己创建和连接它们。

如果您可以实例化要测试的类,并通过构造函数和/或setter getter手动注入它所需的所有依赖项,那么您就不需要在测试中使用Spring

但是,如果您的bean:

  • 使用带有
    @Autowired
    @Value
    注释的私有字段,但不使用相应的getter/setter
  • 这取决于许多其他豆类
  • 要测试的行为取决于Spring AOP/代理(例如,使用
    @Transactional
    @Cacheable
  • 然后您将需要Spring来连接bean。我个人更喜欢为这些情况定义一个最小的
    @配置

    再次,如果您的bean满足列表中的条件,则应考虑重构bean,以最小化其依赖关系并促进测试。