Spring Boot propertiesプロファイルを取得する

10409 ワード

前書き:プロジェクトでは、配置をpropertiesに書くことが多く、配置時には異なる環境を切り替えて正しい配置のパラメータを選択する必要があります.mq redisなどの第三者構成を新たに作成する必要があります.プロジェクトで参照してください.
1.Springの環境なので、当然ながらまずSpring環境を構築する必要があります.
package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2016/10/13.
 */
@Component
public class ValueTest {
    public String name = "        ";
    @Autowired
    public Environment env;//     application.properties    
    @Value("       ")//       
    public String test1;
    @Value("#{systemProperties['os.name']}")//      
    public String test2;
    @Value("#{ T(java.lang.String).valueOf(111)}")//        
    public String test3;
    @Value("#{valueTest.name}")//        
    public String test4;
    @Value("${name}")//     PropertySourcesPlaceholderConfigurer Bean  properties    
    public String test5;

}
注意が必要なのは通過です. EvironmentオブジェクトはSpringbootのpropertieファイルのパラメータしか取得できません. appication-dev.properties.もしappicationの先頭のプロファイルでないなら、propertiesのパスを個別に指定する必要があります.
@PropertySource("classpath:config.properties")//       properties
前と同じであれば、統一して配置できます.
@ConfigrationPropties(prefix) = 「spring.wnagnian」、locations = 「classipath:config/xx.properties」)  
 
2.そのまま使うなら @Value(“$name]”)で構成されている値を取るには、設定が必要です. PropertySources PlaceholderConfigrerを用いてpropertiesファイルを導入します.
package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;

/**
 * Created by Administrator on 2016/10/13.
 */
@Configuration
public class PropertiesConfig {

    @Bean
    public PropertySourcesPlaceholderConfigurer createPropertySourcesPlaceholderConfigurer() {
        ClassPathResource resource = new ClassPathResource("config.properties");
        PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        propertyPlaceholderConfigurer.setLocation(resource);
        return propertyPlaceholderConfigurer;
    }
}
Spring xmlの設定であれば
   <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
       <property name="locations">  
           <list>  
               <value>classpath:config.propertiesvalue>  
           list>  
       property>  
    bean>  
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">  
        <property name="properties" ref="configProperties" />  
    bean>  
値を取る
@Value("#{configProperties['name']}")
private String name;