spring 读取properties文件
spring 读取properties文件
spring 版本:4.3.2.RELEASE
注解方式
使用PropertySource
Java代码
package com.stub.conf; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; /** * Created by 黄威 on 9/18/16.<br > */ @Configuration @PropertySource({"classpath:/com/app.properties","classpath:/${appPath}/app2.properties"}) //@PropertySources({ // @PropertySource("classpath:/com/app.properties"), // @PropertySource("classpath:/${appPath}/app2.properties") //}) public class EnvMyBean { @Autowired Environment env; public String getProperty(String key){ return env.getProperty(key); } }
说明:
变量${appPath}是从第一个配置文件(classpath:/com/app.properties)中读取的.
注意:低版本(例如3.2.3.RELEASE)的spring 是无法读取${appPath}的
如何使用呢?
在控制器中注入EnvMyBean即可.

profile
适用场景:
(a)测试环境,使用@ActiveProfiles 指定profile
Java代码
@ActiveProfiles(profiles = "dev") public class DevConfigTest { //code here }
(b)不同的环境使用不同的配置
通过配置web.xml:
Xml代码
<context-param> <param-name>spring.profiles.active</param-name> <param-value>DOUBLEUPMINT</param-value> </context-param>
(c)通过程序指定
Java代码
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.getEnvironment().setActiveProfiles("dev"); ctx.register(SomeConfig.class, StandaloneDataConfig.class, JndiDataConfig.class); ctx.refresh();
也可以重载全局监听器:
Java代码
import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.ServletContextEvent; /** * Created by 黄威 on 9/18/16.<br > */ public class ApplicationListener extends ContextLoaderListener { public ApplicationListener(WebApplicationContext context) { super(context); ConfigurableEnvironment environment = (ConfigurableEnvironment) context.getEnvironment(); System.out.println("ApplicationListener contructor"); System.out.println(environment); } public ApplicationListener() { super(); } @Override public void contextInitialized(ServletContextEvent event) { super.contextInitialized(event); WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()); ConfigurableEnvironment environment = (ConfigurableEnvironment) ctx.getEnvironment(); System.out.println(environment); environment.setActiveProfiles("production"); } }
使用PropertyPlaceholderConfigurer 需要在xml配置
Xml代码
<bean id="PropertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/app.properties</value>
</list>
</property>
</bean>
参考:http://javabeat.net/profile-annotation-spring-4/

浙公网安备 33010602011771号