遇到Spring Autowiring问题。我有一个Integration Test类声明如下:
@ContextConfiguration(classes = TestConfig.class, loader = AnnotationConfigContextLoader.class)
public abstract class BaseIntegrationTest
extends AbstractTestNGSpringContextTests {
@Autowired
protected TestProperties properties;
//... more stuff here
}
Context配置如下所示:
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = {"com.ourcompany.myapp.it"},
excludeFilters = @ComponentScan.Filter(value = com.inin.wfm.it.config.ConfigPackageExcludeFilter.class, type = FilterType.CUSTOM))
public class TestConfig {
private TestProperties testProperties;
private PropertyService propertyService;
//This both creates and registers the bean with Spring
@Bean
public TestProperties getTestProperties() throws IOException {
if (testProperties == null) {
testProperties = new TestProperties(propertyService());
}
return testProperties;
}
@Bean
public PropertyService propertyService() throws IOException {
if (propertyService == null) {
AppAdminConfig config = new AppAdminConfig.Builder(PropertyService.getEnvironment(), TestConfigKey.ApplicationId)
.checkPropertyHasValue(GlobalConfigKey.KafkaBrokerList.key())
.checkPropertyHasValue(GlobalConfigKey.ZookeeperList.key())
.build();
propertyService = new PropertyService(config.getPropertiesConfig());
propertyService.initialize();
}
return propertyService;
}
}
这是我遇到麻烦的豆子:
@Configurable
public class TestProperties {
private PropertyService propertyService;
public TestProperties(PropertyService propertyService) {
this.propertyService = propertyService;
}
public String getCacheUri(){
return propertyService.getPropertyRegistry().getString(TestConfigKey.CacheUri.key(), Default.CACHE_URI);
}
}
我有多个扩展BaseIntegrationTest的Test实现类。所有这些都有一个对它们的TestProperties字段的有效引用,但是其中一个测试实现类正在获取Null指针并在尝试引用它时抛出NPE。
所以问题是,为什么Spring @Autowire
适用于扩展相同基类的3个不同的类,但为第四个连接null
?在任何实现中都没有其他配置逻辑。
对于MCVE完整性,这是我的impl类
的基础public class CacheIT
extends BaseIntegrationTest {
@Test
public void testUserCache() throws InterruptedException, ExecutionException, TimeoutException {
String uri = properties.getCacheUri() //TODO - NPE here
}
}
我知道没有太多事情要继续......我已经和Spring一起工作了很长时间,以前没有看到它做过这种事情。根据我能看到的一切,它应该起作用。