`

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>
          
            <!--打包 解决 SpringBoot 没有主清单属性-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
          

        </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!";
    }
   
  
    //响应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 {
// ...
}

<!--logback中区分环境 见logback文-->
<springProfile name="dev">
</springProfile>

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

   
    @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框架入门&源码demo.zip

    此外,SpringBoot还支持命令行参数、环境变量和配置文件(如application.properties或application.yml)来定制应用的行为。 在源码分析方面,SpringBoot的自动配置机制是通过`@Configuration`和`@Conditional`注解...

    springboot_properties配置项

    springboot_properties配置项

    SpringBoot整合JDBC&Druid;数据源示例

    接下来,我们需要在SpringBoot的配置文件`application.yml`或`application.properties`中配置Druid数据源。这里以`application.yml`为例: ```yaml spring: datasource: type: ...

    SpringBoot第 5 讲:SpringBoot+properties配置文件读取

    SpringBoot加载配置文件的顺序是:命令行参数 &gt; 系统属性 &gt; `@PropertySource` &gt; `application.yml`/`application.properties`(根据profile) &gt; `bootstrap.yml`/`bootstrap.properties`。注意,`bootstrap....

    SpringBoot中的Profile配置的使用示例源码

    - 在`application.properties`或`application.yml`中定义多个profile,如`application-dev.properties`和`application-prod.properties`,分别对应开发和生产环境。 - 使用`spring.profiles.active`属性激活...

    Springboot:springboot-练习所用

    SpringBoot 是一个基于Java的轻量级框架,它简化了Spring应用的初始搭建以及开发过程。这个项目"Springboot:springboot-练习所用"显然旨在帮助开发者通过实践来掌握SpringBoot的核心特性和使用方式。下面我们将深入...

    SpringBoot:springboot基础服务

    2.3将属性文件装配成一个bean,@ ConfigurationProperties(前缀=“ springboot.properties”)3.在spring boot中转换会加载(2的延申)(资源)类路径:/,file:./,file:。 / config /路径下以应用程序命名的...

    SpringBoot:SpringBoot CRUD和内存数据库

    在SpringBoot应用中,只需在配置文件(`application.properties`)中添加相关配置,如数据库连接URL,就可以使用H2。此外,H2还提供了一个Web界面,可以方便地查看和管理数据库内容。 在实际项目中,我们还会使用...

    springboot:springboot演示

    在`springboot-main`目录下,应该有一个`src/main/resources`文件夹,其中的`application.properties`或`application.yml`文件会配置内嵌服务器的相关属性。 4. **主启动类(Main Application Class)** 通常,...

    springboot:springboot源码分析

    - SpringBoot支持YAML和Properties两种格式的配置文件,YAML更易读,而Properties更传统。配置文件的加载顺序和优先级也是分析的重点。 5. **条件注解(Conditional Annotation)** - 如`@ConditionalOnClass`, `...

    springboot:springboot学习

    SpringBoot的配置主要通过application.properties或application.yml文件进行。这些文件中的配置项会被自动加载到Spring的Environment中。同时,SpringBoot允许通过命令行参数、系统属性、环境变量等方式进行动态配置...

    SpringBoot快速入门.zip

    SpringBoot快速入门.zip是一个针对Java开发者的压缩包,旨在帮助初学者快速掌握SpringBoot框架的基础应用。SpringBoot是由Pivotal团队开发的,它简化了Spring应用的初始搭建以及开发过程,通过内置的默认配置,使得...

    springboot:存储springboot代码

    SpringBoot是Java开发中的一个流行框架,由Pivotal团队创建,旨在简化Spring应用程序的初始设置和常规配置。它集成了大量常用的Java库,如数据访问、安全、Web服务等,使得开发者可以快速构建可运行的Java应用。在这...

    dubbo_springboot:dubbo整合springboot

    【标题】:“dubbo_springboot:Dubbo与SpringBoot的整合应用” 在现代Java开发中,SpringBoot因其快速启动、简化配置等特性受到了广泛欢迎,而Dubbo作为一款高性能、轻量级的服务治理框架,常用于构建微服务架构。...

    springboot_properties_multienv

    实际项目开发过程中会用到多个环境,比如dev,test,product环境,不同的环境可能使用不同参数,为便于部署提高效率,本代码通过properties配置文件来实现多环境的配置。 对应博客地址:...

    SpringBoot:尝试SpringBoot

    在下载的 `SpringBoot-master` 压缩包中,你可能找到了一个 SpringBoot 项目的源码结构,包括 `src/main/java` 下的主程序类,`src/main/resources` 下的应用配置文件(application.properties 或 application.yml)...

    SpringBoot:SpringBoot示例

    SpringBoot支持使用YAML(一种更易读的配置格式)和传统的Properties文件进行配置。这些配置可以通过`@Value`注解或者@ConfigurationProperties绑定到Bean中。 **Spring Initializr**: Spring Initializr是一个...

    springboot初学者必备代码.zip

    011-springboot-commandlinerunner 012-sprinboot-interceptor 013-springboot-servlet 014-springboot-filter 015-springboot-character-filter 016-springboot-character-properties 017-springboot-mapper 018-...

    hx-springboot:初学springboot搭建的项目

    《hx-springboot:初识SpringBoot项目构建》 在当今的Java开发领域,SpringBoot框架因其简洁的配置、快速的开发效率以及强大的生态系统而备受推崇。本项目“hx-springboot”是一个针对初学者搭建的SpringBoot应用,...

    Flyway-Demo-SpringBoot:测试springbootvớiflyway

    【标题】"Flyway-Demo-SpringBoot:测试springbootvớiflyway"是一个关于在SpringBoot项目中集成和测试Flyway数据库迁移工具的示例。这个项目旨在展示如何利用Flyway进行数据库版本控制,确保数据库结构与应用程序...

Global site tag (gtag.js) - Google Analytics