springboot:properties&profile&CommandLineRunner

pom.xml:
=======================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>springboot</groupId>
<artifactId>springboot-properties</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-properties :: Spring boot 配置文件</name>

<!-- Spring Boot 启动父依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>

<dependencies>
<!-- Spring Boot Web 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- Spring Boot Test 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<!-- Junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>1.4.2.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
[color=red]
<!--打包 解决 SpringBoot 没有主清单属性-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
[/color]
</plugins>
</build>

<distributionManagement>
<repository>
<id>movikr-releases</id>
<url>http://nexus.mapollo.com/nexus/content/repositories/releases/</url>
</repository>
<snapshotRepository>
<id>movikr-snapshots</id>
<url>http://nexus.mapollo.com/nexus/content/repositories/snapshots/</url>
</snapshotRepository>
</distributionManagement>
</project>
=======================================
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!";
}

[color=red]
//响应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;
}
[/color]

}

=======================================
test.properties
=======================================
test.t1=aaaa1
test.t2=aaaa2
test.t3=aaaa3
======================================
[color=red]
//如果不添加@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
[/color]

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

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

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

<!--logback中区分环境 见logback文-->
<springProfile name="dev">
</springProfile>
[/color]
=======================================
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 应用启动类
* <p>
* 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);
}

[color=red]
@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();
}
[/color]
}
===================================
1.执行Application main方法 会按照applicaition.properties主配置文件 中激活dev来读取application-dev.properties输出homeProperties.toString()

2.打包方式 mvn clean package
[color=red]
java -Xms512m -Xmx1024m -jar springboot-properties-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod --name="Spring" --server.port=9090 -Dlogging.path=/tmp
[/color]
按照prod输出
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值