我有两个弹簧配置文件:开发和生产。
应该有一个公共属性文件(放在classpath:properties/common/*.properties
中),该文件将被配置文件的属性文件覆盖(放在classpath:properties/development/*.properties
中。
这是我的上下文配置片段,以澄清我的意图:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.example.entities.*" />
<property name="hibernateProperties" ref="hibernateProperties" />
</bean>
<beans profile="development">
<context:property-placeholder location="classpath:properties/development/jdbc.properties" />
<bean id="hibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="ignoreResourceNotFound" value="true" />
<property name="location" value="classpath:properties/development/hibernate.properties" />
</bean>
</beans>
<beans profile="production">
<context:property-placeholder location="classpath:properties/production/jdbc.properties" />
<bean id="hibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="ignoreResourceNotFound" value="true" />
<property name="location" value="classpath:properties/production/hibernate.properties" />
</bean>
</beans>
目前在某处没有共同的属性。如何将公共属性文件与jdbc.properties
和hibernate.properties
的每个配置文件中的公共属性文件合并?
答案 0 :(得分:1)
我已经使用了JavaConfig:
@Configuration
@Profile("development")
public class DevelopmentConfig {
public @Bean String profile() {
return "development";
}
}
@Configuration
@Profile("production")
public class ProductionConfig {
public @Bean String profile() {
return "production";
}
}
public class PropertyUtils {
public static Properties getProperties(String profile, String filename) throws IOException {
Properties ret = new Properties();
ClassPathResource resource;
resource = new ClassPathResource("properties/common/" + filename + ".properties");
ret.putAll(PropertiesLoaderUtils.loadProperties(resource));
resource = new ClassPathResource("properties/" + profile + "/" + filename + ".properties");
if (resource.exists()) {
ret.putAll(PropertiesLoaderUtils.loadProperties(resource));
}
return ret;
}
}
@Configuration
public class MainConfig {
private @Autowired String profile;
// Here you can use: PropertyUtils.getProperties(profile, "jdbc"))
}
答案 1 :(得分:0)
这应该让你入门
<bean id="allProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="singleton" value="true"/>
<property name="ignoreResourceNotFound" value="true"/>
<property name="locations">
<list>
<value>classpath*:default.properties</value>
<value>classpath*:overrides.properties</value>
<value>file:${APP_HOME}/**/*.properties</value>
</list>
</property>
</bean>