是否有一种方法可以防止Spring配置中的依赖注入?



我正在一个Spring项目中工作,其中单元测试有自己的配置,称为UnitTestConfig,其中有几个bean定义类似于主应用程序文件(几乎是副本)。保持结构完整,我在主应用服务器代码中做了一些改变,但是这会在UnitTestConfig中抛出错误,因为它没有注入所需的bean。这些bean在单元测试中不使用,是否有一种方法可以防止UnitTestConfig试图注入这些?这是一个大的级联效应,因为a注入,B注入C,等等,并且它期待所有这些bean。我可以告诉Spring配置,我不想注入这些bean或让它们为空吗?

@Configuration
public class UnitTestConfig {
@Inject
private Environment env;
@Bean
public A a() {
return new A();
}

为了在需要时不注入A的字段,我在字段上添加了@Lazy,它似乎可以工作,但我更希望对此进行任何修改,以便在测试配置端,而不是修改主要应用程序代码只是为了修复测试问题。有什么建议吗?

这叫做循环bean依赖。有很多方法可以解决这个问题。在构造函数参数中使用@Lazy注释。不要使用构造器注入,而要使用setter注入或In应用。属性文件写入spring.main.allow-bean-definition-overriding = true

这是大多数应用程序中非常常见的问题,随着应用程序的增长,很难添加具有公共配置的单元测试。运行单元测试变成了一场噩梦,因为你必须处理不必要的上下文加载。

我们最终开始使用测试概要文件,以解决加载不必要bean的问题。并且仅为某些配置文件加载bean。像这样-

我如何禁用创建bean与@Component注释在Spring?

但是这会产生它自己的问题——创建多个概要文件和管理这些概要文件。如果管理配置文件不是问题,这可以帮助您。

或者,我们停止使用公共上下文进行单元测试,并开始使用静态测试上下文类隔离地测试类,并模拟所有非必需的bean。像这样-

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class SomeJavaClassTest {
@Autowired
private Bean1 bean1;
@Autowired
private Bean2 bean2;
@Autowired
private Bean3 bean3;

@test
public void method1Test() throws Exception {
}

@test
public void method2Test() throws Exception {
}

@Configuration
static class Config {

@Bean
public Bean1 bean1() {
return Mockito.mock(Bean1.class);
}
@Bean
public Bean2 bean2() {
return new SomeJavaClass();
}

@Bean
public Bean3 bean3() {
return Mockito.mock(Bean3.class);
}

@Bean
public PropertySourcesPlaceholderConfigurer properties() throws Exception {
PropertySourcesPlaceholderConfigurer propertyPlaceholder = new PropertySourcesPlaceholderConfigurer();
// setup properties that needs to be injected into the class under test
Properties properties = new Properties();
properties.setProperty("some.required.properties", "");

propertyPlaceholder.setProperties(properties);
return propertyPlaceholder;
}
}

最新更新