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

    xiaoxiao2021-04-15  33

    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

    配置类注解 : 使用 

    @ConfigurationPropertiesprefix : 获取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); } }

    结果 : 

    p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco }

    ["hehe","haha"]

     

    参考文献

    p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px "Courier New" }

    springboot配置

     

    springboot中文文档

    转载请注明原文地址: https://ju.6miu.com/read-671962.html

    最新回复(0)