springboot 学习笔记(二)--- properties 配置

 

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中文文档

转载于:https://www.cnblogs.com/chenmo-xpw/p/6106788.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值