【Java从零到架构师第③季】【41】SpringBoot-配置文件

【Java从零到架构师第③季】【41】SpringBoot-配置文件,第1张


持续学习&持续更新中…

守破离


【Java从零到架构师第③季】【41】SpringBoot-配置文件_YAML_lombok_设置BannerL
    • 应用程序配置文件
    • 配置文件的内容
    • 运行参数、VM选项
    • application配置文件
    • lombok
    • YAML
    • YAML—属性绑定1
    • YAML—属性绑定2
    • YAML—构造方法绑定
    • YAML—@ConfigurationProperties与@Bean
    • YAML—宽松绑定
    • 拆分配置文件
    • 设置Banner
    • 注意
    • 参考

应用程序配置文件

比如:

注意:

  • 是项目(project)的根路径,而不是模块(module)的根路径
  • Maven管理的项目,resources目录下的文件会被编译到classpath(target/calsses/)下
配置文件的内容

https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-application-property-files

server.port=8080
server.servlet.context-path=/sb_cf

运行参数、VM选项

不想通过命令行启动jar,而是想通过IDEA设置让IDEA启动项目的话,配置步骤如下:

或者通过VM选项:

application配置文件

application.properties:

plain=normal_plain
names=lpruoyu, lp, ruoyu
scores={'lpruoyu':111, 'lp':222, 'ruoyu':333}
homes={'lpruoyu':'SX', 'lp':'BJ', 'ruoyu':'NF'}
@RestController
public class TestController {
    @Value("${plain}")
    private String plain;
    @Value("${names}")
    private String[] names;
//    List、Set和数组一样
//    private List names;
//    private Set names;

    @Value("#{${scores}}")
    private Map<String, Integer> scores;
    @Value("#{${homes}}")
    private Map<String, String> homes;

    @GetMapping("/test")
    public String test() {
        for (String name : names) {
            System.out.println(name);
        }
        scores.forEach((k, v) -> {
            System.out.println(k + "_" + v);
        });
        homes.forEach((k, v) -> {
            System.out.println(k + "_" + v);
        });
        return "running success!";
    }
}
lombok

官网:https://projectlombok.org/

我的这个IDEA版本已经自动安装好了lombok插件,因此不用安装插件。

lombok依赖:

	<dependency>
	    <groupId>org.projectlombokgroupId>
	    <artifactId>lombokartifactId>
	    <scope>providedscope>
	dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-configuration-processorartifactId>
    dependency>

@Component
@ConfigurationProperties("person")
@Data
// @Data >= @Getter + @Setter + @ToString
public class Person {
    private Integer id;
    private Integer age;
    private String name;

    // List、Set、数组,yml的写法是一样的
    private String[] nickNames;
}
person:
  id: 1
  age: 22
  name: lpruoyu
  nick-names:
    - lp2
    - ruoyu2
    - lpx2
#  nick-names: [lp1, ruoyu1, lpx1]
#  nick-names: lp, ruoyu, lpx
YAML

server:
  port: 8888
  servlet:
    context-path: /yml

#name: lp
name: "lp\truoyu"
@RestController
public class TestController {
    @Value("${name}")
    private String name;

    @GetMapping("/test")
    public String test() {
        System.out.println(name);
        return "test" + name;
    }
}

YAML—属性绑定1

属性绑定的本质是通过setter方法设置的

第一种绑定方式:

application.yml:

id: 10
age: 22
@Component
public class Person {
    @Value("${id}")
    private Integer id;
    @Value("${age}")
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", age=" + age +
                '}';
    }
}
@RestController
public class TestController {
    @Value("${name}")
    private String name;
    @Autowired
    private Person person;

    @GetMapping("/test")
    public String test() {
        System.out.println(person);
        return "test" + name;
    }
}

第二种绑定方式:

application.yml:

person:
  id: 1
  age: 22
@Component
@ConfigurationProperties("person")
public class Person {
    private Integer id;
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", age=" + age +
                '}';
    }
}
YAML—属性绑定2

person:
  id: 1
  name: lpruoyu
  nick-names: [ lp1, ruoyu1, lpx1 ]
  dog:
    age: 10
    name: hz
  dogs:
    - age: 10
      name: hz1
    - age: 11
      name: hz2
  hobbies:
    - childhood: run
    - youth: basketball
    - manhood: infinity
#  hobbies: {
#    childhood: run,
#    youth: basketball,
#    manhood: infinity
#  }
@Component
@ConfigurationProperties("person")
@Data
public class Person {
    private Integer id;
    private String name;
    // List、Set、数组,yml的写法是一样的
    private String[] nickNames;
    private Map<String, String> hobbies;
    private Dog dog;
    private List<Dog> dogs;

    @Data
    private static class Dog {
        private Integer age;
        private String name;
    }
}
@RestController
public class TestController {
    @Autowired
    private Person person;

    @GetMapping("/test")
    public String test() {
        System.out.println(person);
        return "test";
    }
}

@ConfigurationProperties("student")
// @ConfigurationProperties(prefix = "student")
@Data
public class Student {
    private Integer id;
    private String name;
    // List、Set、数组,yml的写法是一样的
    private String[] nickNames;
    private Map<String, String> hobbies;
    private Dog dog;
    private List<Dog> dogs;

    @Data
    private static class Dog {
        private Integer age;
        private String name;
    }
}
student:
  id: 1
  name: lpruoyu
  nick-names:
    - lp1
    - ruoyu1
    - lpx1
  dog:
    age: 10
    name: hz
  dogs:
    - age: 10
      name: hz1
    - age: 11
      name: hz2
  hobbies:
    - childhood: run
    - youth: basketball
    - manhood: infinity

@RestController
@EnableConfigurationProperties(Student.class)
public class TestController {
    @Autowired
    private Student student;

    @GetMapping("/test")
    public String test() {
        System.out.println(student);
        return "test";
    }
}
YAML—构造方法绑定

cat:
  id: 1
  name: lpruoyu
  nick-names:
    - lp
    - ruoyu
    - lpx
  dog:
    age: 10
    name: hz
  dogs:
    - age: 10
      name: hz
    - age: 11
      name: hz
  hobbies:
    - childhood: run
    - youth: basketball
    - manhood: infinity
//@ConfigurationProperties(prefix = "cat")
// @ConfigurationProperties(value = "cat")
@ConfigurationProperties("cat")
// 由于是通过构造方法注入的,因此不需要getter、setter,于是不使用@Data
@ToString
@ConstructorBinding
public class Cat {
    private Integer id;
    private String name;
    private String[] nickNames;
    private Map<String, String> hobbies;
    private Dog dog;
    private List<Dog> dogs;

    public Cat(Integer id, String name, String[] nickNames, Map<String, String> hobbies, Dog dog, List<Dog> dogs) {
        this.id = id;
        this.name = name;
        this.nickNames = nickNames;
        this.hobbies = hobbies;
        this.dog = dog;
        this.dogs = dogs;
    }

    @ToString
    @ConstructorBinding
    public static class Dog {
        private Integer age;
        private String name;

        public Dog(Integer age, String name) {
            this.age = age;
            this.name = name;
        }
    }
}
@RestController
@EnableConfigurationProperties(Cat.class)
public class TestController {
    @Autowired
    private Cat cat;

    @GetMapping("/test")
    public String test() {
        System.out.println(cat);
        return "test";
    }
}

YAML—@ConfigurationProperties与@Bean

@Data
public class Person {
    private Integer id;
    private String name;
    private String[] nickNames;
    private Map<String, String> hobbies;
    private Dog dog;
    private List<Dog> dogs;

    @Data
    public static class Dog {
        private Integer age;
        private String name;
    }
}
person:
  id: 1
  name: lpruoyu
  nick-names:
    - lp
    - ruoyu
    - lpx
  dog:
    age: 10
    name: hz
  dogs:
    - age: 10
      name: hz
    - age: 11
      name: hz
  hobbies:
    - childhood: run
    - youth: basketball
    - manhood: infinity
@Configuration
public class BeanConfiguration {
    @Bean
    @ConfigurationProperties("person")
    public Person person() {
        return new Person();
    }
}
@RestController
public class TestController {
    @Autowired
    private Person person;

    @GetMapping("/test")
    public String test() {
        System.out.println(person);
        return "test";
    }
}
YAML—宽松绑定

拆分配置文件

@Component
@ConfigurationProperties("jdbc")
@Data
public class JdbcProperties {
    private String driverClassName;
    private String username;
    private String password;
    private String url;
}
@RestController
public class TestController {
    @Autowired
    private JdbcProperties jdbcProperties;

    @GetMapping("/test")
    public String test() {
        return jdbcProperties.toString();
    }
}

application.yml:

# 公共配置

spring:
  profiles:
    active: development
server:
  port: 8888
  servlet:
    context-path: /yml

---

# 开发环境
spring:
  profiles: development
jdbc:
  driver-class-name: com.mysql.jdbc.Driver
  url: jdbc:mysql://localhost:3306/test_mybatis?useSSL=false
  username: employee01
  password: employee01

---

# 上线环境
spring:
  profiles: production
jdbc:
  driver-class-name: com.mysql.jdbc.Driver
  url: jdbc:mysql://localhost:3306/lp_resume?useSSL=false
  username: root
  password: root

application.yml:

# 公共配置
spring:
  profiles:
    active: development
server:
  port: 8080

application-development.yml:

# 开发环境
jdbc:
  driver-class-name: com.mysql.jdbc.Driver
  url: jdbc:mysql://localhost:3306/test_mybatis?useSSL=false
  username: employee01
  password: employee01

application-production.yml:

# 上线环境
jdbc:
  driver-class-name: com.mysql.jdbc.Driver
  url: jdbc:mysql://localhost:3306/lp_resume?useSSL=false
  username: root
  password: root

如果公共配置文件(application.yml)内容过多的话,还可以将公共配置文件的内容再拆分出来:

application.yml:

# 公共配置
spring:
  profiles:
    active:
      - development
      - port
      - ctx
#    active: development, port, ctx
#    active: [development, port, ctx]

application-ctx.yml:

server:
  servlet:
    context-path: /yml

application-port.yml:

server:
  port: 8080
设置Banner
  • Banner官网说明:https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-banner
  • Banner生成:http://patorjk.com/software/taag

resources/banner.txt:

  _
 | |
 | |  _ __    _ __   _   _    ___    _   _   _   _
 | | | '_ \  | '__| | | | |  / _ \  | | | | | | | |
 | | | |_) | | |    | |_| | | (_) | | |_| | | |_| |
 |_| | .__/  |_|     \__,_|  \___/   \__, |  \__,_|
     | |                              __/ |
     |_|                             |___/
    ┌─┐       ┌─┐
 ┌──┘ ┴───────┘ ┴──┐
 │                 │
 │       ───       │
 │  ─┬┘       └┬─  │
 │                 │
 │       ─┴─       │
 │                 │
 └───┐         ┌───┘
     │         │
     │         │    ${AnsiColor.BRIGHT_MAGENTA}神兽保佑,永无bug${AnsiColor.DEFAULT}
     │         │
     │         └──────────────┐
     │                        │
     │                        ├─┐
     │                        ┌─┘
     │                        │
     └─┐  ┐  ┌───────┬──┐  ┌──┘
       │ ─┤ ─┤       │ ─┤ ─┤
       └──┴──┘       └──┴──┘
${AnsiColor.BRIGHT_YELLOW}
                    .::::.
                  .::::::::.
                 :::::::::::
             ..:::::::::::'
           '::::::::::::'
             .::::::::::
        '::::::::::::::..
             ..::::::::::::.
           ``::::::::::::::::
            ::::``:::::::::'        .:::.
           ::::'   ':::::'       .::::::::.
         .::::'      ::::     .:::::::'::::.
        .:::'       :::::  .:::::::::' ':::::.
       .::'        :::::.:::::::::'      ':::::
      .::'        :::::::::::::::'         ::::.
  ...:::         ::::::::::::::'             ::::.
 ````':.          ':::::::::'                  ::::..
                    ':::::'                    ':'````..
${AnsiColor.DEFAULT}
                    .::::.
                  .::::::::.
                 :::::::::::
             ..:::::::::::'
           '::::::::::::'
             .::::::::::
        '::::::::::::::..
             ..::::::::::::.
           ``::::::::::::::::
            ::::``:::::::::'        .:::.
           ::::'   ':::::'       .::::::::.
         .::::'      ::::     .:::::::'::::.
        .:::'       :::::  .:::::::::' ':::::.
       .::'        :::::.:::::::::'      ':::::
      .::'        :::::::::::::::'         ::::.
  ...:::         ::::::::::::::'             ::::.
 ````':.          ':::::::::'                  ::::..
                    ':::::'                    ':'````..
spring-boot.version : ${spring-boot.version}

运行效果:

注意
  • 也可以在IDEA中配置Program arguments:--spring.profiles.active=development,port,ctx来配置
  • 对应的VM options:-Dspring.profiles.active=development,port,ctx
  • 可以在Program arguments(或者VM options)中配置:--server.port=8888,使用这两种方式设置配置信息的优先级是最高的。
  • Program arguments和VM options的多个配置使用空格隔开,例如:--spring.profiles.active=production,port,ctx --server.port=9999
  • 当然也可以通过Program arguments和VM options传入其他配置信息:
    • Program arguments:--name=lp --age=20
    • VM options:-Dname=lp -Dage=20
    • 使用@Value("name")@Value("age")就可以注入到对象的属性中使用。
参考

小码哥-李明杰: Java从0到架构师③进阶互联网架构师.


本文完,感谢您的关注支持!


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/725218.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)

保存