Java Spring:无法在单元测试中使用属性占位符
我正在开发一个Spring4.0REST应用程序,它工作正常,但当我尝试进行一些测试时,它无法从占位符读取属性值(如果我正常运行应用程序,它们工作正常) 应用程序的一些属性来自文件,其他属性来自数据库,所以我配置了一个PropertiesPropertySource从数据库中读取它们。我无法通过xml对其进行配置,因此我在@Configuration类中进行了配置:Java Spring:无法在单元测试中使用属性占位符,java,spring,junit,properties,Java,Spring,Junit,Properties,我正在开发一个Spring4.0REST应用程序,它工作正常,但当我尝试进行一些测试时,它无法从占位符读取属性值(如果我正常运行应用程序,它们工作正常) 应用程序的一些属性来自文件,其他属性来自数据库,所以我配置了一个PropertiesPropertySource从数据库中读取它们。我无法通过xml对其进行配置,因此我在@Configuration类中进行了配置: public class AppConfig { private static final Logger logger =
public class AppConfig {
private static final Logger logger = LoggerFactory.getLogger(AppConfig.class);
@Inject
private org.springframework.core.env.Environment env;
@Autowired
private DataSource dataSource;
@PostConstruct
public void initializeDatabasePropertySourceUsage() {
MutablePropertySources propertySources = ((ConfigurableEnvironment) env).getPropertySources();
try {
DatabaseConfiguration databaseConfiguration = new DatabaseConfiguration(dataSource, "[TABLE]", "property", "value");
CommonsConfigurationFactoryBean commonsConfigurationFactoryBean = new CommonsConfigurationFactoryBean(databaseConfiguration);
Properties dbProps = (Properties) commonsConfigurationFactoryBean.getObject();
PropertiesPropertySource dbPropertySource = new PropertiesPropertySource("dbPropertySource", dbProps);
propertySources.addFirst(dbPropertySource);
} catch (Exception e) {
logger.error("Error during database properties setup:"+e.getMessage(), e);
throw new RuntimeException(e);
}
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
在测试类中,我加载带有以下注释的上下文配置:
@ContextConfiguration(类={TestConfig1.class,AppConfig.class,TestConfig2.class})
当我混合使用XML和java配置时,我必须创建TestConfigX类,这些类使用以下注释加载XML:
@ImportResource([配置xml的路径])
- TestConfig1具有DatasourceBean定义,并且工作正常
- AppConfig配置PropertiesPropertySource以从DB读取占位符
- TestConfig2配置应用程序的其余部分,它使用占位符(@Value=${XXXX}),但无法读取值:无法解析占位符XXXX
我做错了什么?您应该使用
ApplicationContextInitializer
向环境添加PropertySource
。您当前的设置太迟了。您好,我正按照您的建议做,但数据库PropertySource依赖于为根上下文提供的数据源,由于ApplicationContextInitializer在根上下文之前被invike,因此数据源为null,并且它失败纠正,因此您必须手动创建/获取它,而不是依赖于该上下文。Thx,我按照您的建议做了。手动实例化数据源不是很干净,但至少可以工作