首页 > 技术文章 > springboot 学习笔记(二)--- properties 配置

chenmo-xpw 2016-11-27 18:35 原文

 

springboot可以提供了多种方式配置properties。

 

一、Java System.setProperty(k, v)

System.setProperty("myname", "Java_System_name");

 

二、在classpath目录下创建配置文件 application.properties

文件内容格式是 KV格式

myname=classpath_name

 

三、支持嵌套注解

application.properties

db=db
jdbc.username=root
jdbc.password=root

注解主类

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties
public class MysqlConfig {

    private String db;

    private Jdbc jdbc;

    public String getDb() {
        return db;
    }

    public void setDb(String db) {
        this.db = db;
    }

    public Jdbc getJdbc() {
        return jdbc;
    }

    public void setJdbc(Jdbc jdbc) {
        this.jdbc = jdbc;
    }

}

附类

public class Jdbc {
    private String username;

    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

springboot 会自动解析jdbc开头的属性,和注解类jdbc映射

 

四、创建yml文件配置

首先, pom需要依赖

<dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-configuration-processor</artifactId>  
        <optional>true</optional>  
 </dependency> 

 

my:
  server:
    - hehe
    - haha

配置类注解 : 使用 

@ConfigurationProperties

prefix : 获取yml文件的my配置项
@Component("serverConfig")
@ConfigurationProperties(prefix = "my")
public class ServerConfig {

    private List<String> server = new ArrayList<String>();

    public List<String> getServer() {
        return server;
    }

    public void setServer(List<String> server) {
        this.server = server;
    }

}

测试 : 

@RestController : spring路由请求,直接将结果返回给请求者
@EnableAutoConfiguration : springboot启动入口
@ComponentScan : 扫描注解
@RestController
@EnableAutoConfiguration
@ComponentScan
public class Application {

    @Autowired
    private ServerConfig serverConfig;

    @RequestMapping("/")
    public String index() {

        getServerConfig();

        return "hello, spring boot" ;
    }

    public void getServerConfig() {
        Gson gson = new Gson();

               System.out.println(gson.toJson(serverConfig.getServer()));
    }

    public static void main(String[] args) {


        SpringApplication.run(Application.class, args);

    }
}

结果 : 

["hehe","haha"]

 

参考文献

springboot配置

 

springboot中文文档

推荐阅读