spring 讀取properties文件

分類:IT技術 時間:2016-10-17

spring 讀取properties文件

spring 版本:4.3.2.RELEASE

註解方式

使用PropertySource

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

@ActiveProfiles(profiles = "dev")
public class DevConfigTest {
//code here
}

(b)不同的環境使用不同的配置

通過配置web.xml:

<context-param>
  <param-name>spring.profiles.active</param-name>
  <param-value>DOUBLEUPMINT</param-value>
</context-param>

(c)通過程序指定

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("dev");
ctx.register(SomeConfig.class, StandaloneDataConfig.class, JndiDataConfig.class);
ctx.refresh();

也可以重載全局監聽器:

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");
    }
}

參考:http://javabeat.net/profile-annotation-spring-4/

  • 大小: 315.7 KB
  • 查看圖片附件

Tags: 配置文件 profile spring public return

文章來源:


ads
ads

相關文章
ads

相關文章

ad