springboot:properties&profile&CommandLineRunner

阅读更多
pom.xml:
=======================================

         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

    springboot
    springboot-properties
    0.0.1-SNAPSHOT
    springboot-properties :: Spring boot 配置文件

   
   
        org.springframework.boot
        spring-boot-starter-parent
        1.5.1.RELEASE
   


   
       
       
            org.springframework.boot
            spring-boot-starter-web
       


       
       
            org.springframework.boot
            spring-boot-starter-test
            test
       


       
       
            junit
            junit
            4.12
       

       
            org.springframework.boot
            spring-boot-test
            1.4.2.RELEASE
            test
       

   

   
       
          
           
           
                org.springframework.boot
                spring-boot-maven-plugin
               
                   
                       
                            repackage
                       

                   

               

           

          

       

   


   
       
            movikr-releases
            http://nexus.mapollo.com/nexus/content/repositories/releases/
       

       
            movikr-snapshots
            http://nexus.mapollo.com/nexus/content/repositories/snapshots/
       

   


=======================================
HomeProperties.java
=======================================
@Component("HomeProperties")
@ConfigurationProperties(prefix = "home")
//@ConfigurationProperties(prefix = "home",locations = "classpath:config/home.properties")
public class HomeProperties {

    private String province;

    private String city;

    private String desc;

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }
}
=======================================
TestProperties.java
指定properties文件
=======================================
@Component("TestProperties")
@PropertySource(value="classpath:test.properties", ignoreResourceNotFound=true)
public class TestProperties {

    @Value("${test.t1}")
    private String t1;

    @Value("${test.t2}")
    private String t2;

    @Value("${test.t3}")
    private String t3;

    public String getT1() {
        return t1;
    }

    public void setT1(String t1) {
        this.t1 = t1;
    }

    public String getT2() {
        return t2;
    }

    public void setT2(String t2) {
        this.t2 = t2;
    }

    public String getT3() {
        return t3;
    }

    public void setT3(String t3) {
        this.t3 = t3;
    }
}
=======================================
EnviromentConfig.java
读取环境变量
=======================================
@Configuration
public class EnviromentConfig implements EnvironmentAware{

    private RelaxedPropertyResolver propertyResolver;

    /**
     * 这个方法只是测试实现EnvironmentAware接口,读取环境变量的方法。
     */
    @Override
    public void setEnvironment(Environment env) {
        String str = env.getProperty("server.port");
        System.out.println(str);
        propertyResolver = new RelaxedPropertyResolver(env, "server.");
        String value = propertyResolver.getProperty("port");
        System.out.println(value);

        //读取环境变量
        System.out.println(env.getProperty("JAVA_HOME"));
        System.out.println(env.getProperty("spring.datasource.url"));
        propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
        String url = propertyResolver.getProperty("url");
        System.out.println(url);
    }

}
=======================================
HelloWorldController.java
=======================================
package org.spring.springboot.web;

import org.spring.springboot.property.HomeProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
* Spring Boot HelloWorld 案例
*
* Created by bysocket on 16/4/26.
*/
@RestController
@RequestMapping("/hello")
public class HelloWorldController {
    //注入指定前缀
    @Resource(name = "HomeProperties")
    HomeProperties homeProperties;

    //注入字符串
    @Value("${test.property}")
    private String testProperty

    //注入指定properties文件
    @Resource(name = "TestProperties")
    private TestProperties testProperties;

    //restful
    @RequestMapping(value = "/api/city/{id}", method = RequestMethod.GET)
    public City findOneCity(@PathVariable("id") Long id) {
        return null;
    }

    //测试properties
    @RequestMapping("/say")
    public String sayHello() {
        System.out.println(homeProperties.getCity());
        System.out.println(testProperties.getT1());
        System.out.println(testProperty);
        return "Hello,World111!";
    }
   
  
    //响应json
    //参数{"id":"1","name":"\u60a8\u597d","date":"1498789197040"}
    @RequestMapping(value = "/json", method = {RequestMethod.POST })
    @ResponseBody
    public Student testjson(@RequestBody(required = false)Student data) {
        Student student = new Student();
        student.setId(data.getId());
        student.setDate(data.getDate());
        student.setName(data.getName());
        return student;
    }
   


}

=======================================
test.properties
=======================================
test.t1=aaaa1
test.t2=aaaa2
test.t3=aaaa3
======================================

//如果不添加@configation或者@Component
//执行此类的autowrite时 必须配置@EnableConfigurationProperties({EnableConfigationSettings.class}) 指定此类
@ConfigurationProperties(prefix = "myenv")
public class EnableConfigationSettings {

    private int a;
    private int b;

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }

    public int getB() {
        return b;
    }

    public void setB(int b) {
        this.b = b;
    }
}

@EnableConfigurationProperties({EnableConfigationSettings.class})
public class Application implements CommandLineRunner{}

myenv.a=1
myenv.b=2


=======================================
application.properties
=======================================
server.port=8090
server.session-timeout=30
server.context-path=
server.tomcat.max-threads=0
server.tomcat.uri-encoding=UTF-8


# Spring Profiles Active application-dev.properties默认读取dev文件
spring.profiles.active=dev

@Configuration
@Profile("dev")
public class ProductionConfiguration {
// ...
}





=======================================
application-dev.properties
=======================================
## 家乡属性 Dev
home.province=ZheJiang
home.city=WenLing
home.desc=dev: I'm living in ${home.province} ${home.city}.
test.property=dev
=======================================
application-prod.properties
=======================================
## 家乡属性 Dev
home.province=ZheJiang
home.city=WenLing
home.desc=prod: I'm living in ${home.province} ${home.city}.
test.property=prod
=======================================
Application.java
=======================================
package org.spring.springboot;

import org.spring.springboot.property.HomeProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
* Spring Boot 应用启动类
*


* Created by bysocket on 16/4/26.
*/
// Spring Boot 应用的标识
@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    private HomeProperties homeProperties;

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(Application.class);
        //关闭banner
        application.setBannerMode(Banner.Mode.OFF);
        application.addListeners(new TestListener());
        application.run(args);
    }

   
    @Override
    public void run(String... args) throws Exception {
        System.out.println("\n" + homeProperties.toString());
        //System.out.println(configationSettings.getA());

        //FIXME run的时候加载xml的配置
        //SpringApplication.run("classpath:/META-INF/application-context.xml", args);

        //FIXME 加载启动数据 在implement CommandLineRunner 增加@Order()注解 指定加载顺序
        //code<加载数据>

        System.out.println();
    }
   

}
===================================
1.执行Application main方法 会按照applicaition.properties主配置文件 中激活dev来读取application-dev.properties输出homeProperties.toString()

2.打包方式 mvn clean package

java -Xms512m -Xmx1024m -jar springboot-properties-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod --name="Spring" --server.port=9090 -Dlogging.path=/tmp

按照prod输出

你可能感兴趣的:(springboot,properties,profile)