springboot学习(二)

由于一点事情耽搁了,继续学习吧!这次我的任务主要是学习springboot的属性配置和使用,初学勿喷,谢谢,有什么不对的也请大佬们批评指正!

进入正题:

Spring Boot 允许通过外部配置让你在不同的环境使用同一应用程序的代码,简单说就是可以通过配置文件来注入属性或者修改默认的配置。

我看前人已经归纳好了这些配置方式的优先级,我就直接搬过来了:

  1. 命令行参数
  2. 来自java:comp/env的JNDI属性
  3. Java系统属性(System.getProperties()
  4. 操作系统环境变量
  5. RandomValuePropertySource配置的random.*属性值
  6. jar包外部的application-{profile}.propertiesapplication.yml(带spring.profile)配置文件
  7. jar包内部的application-{profile}.propertiesapplication.yml(带spring.profile)配置文件
  8. jar包外部的application.propertiesapplication.yml(不带spring.profile)配置文件
  9. jar包内部的application.propertiesapplication.yml(不带spring.profile)配置文件
  10. @Configuration注解类上的@PropertySource
  11. 通过SpringApplication.setDefaultProperties指定的默认属性

其实这么多方式,我根本就记不下来,不过介绍还是得写,忘了还能看看呢。

首先来学习命令行参数

看了命令行方式,比较简单,就是在控制台输入java -jar test.jar --xxx=参数值 方式来传递参数,其中参数名为XXX,使用时需要通过--xxx=参数值,多个参数中间用空格

这里需要注意的是,参数名可以使用自定义参数,也可以使用springboot中默认参数。springboot中提供了好多参数,常用的无非是那些服务器配置信息等

这里就先提供一个地址以及列举几个常用的参数,请点击这里查看所有参数列表

 1 # LOGGING
 2 logging.path=/var/logs
 3 logging.file=myapp.log
 4 logging.config= # location of config file (default classpath:logback.xml for logback)
 5 logging.level.*= # levels for loggers, e.g. "logging.level.org.springframework=DEBUG" (TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF)
 6 
 7 # EMBEDDED SERVER CONFIGURATION (ServerProperties)
 8 server.port=8080
 9 server.address= # bind to a specific NIC
10 server.session-timeout= # session timeout in seconds
11 server.context-parameters.*= # Servlet context init parameters, e.g. server.context-parameters.a=alpha
12 server.context-path= # the context path, defaults to '/'
13 server.servlet-path= # the servlet path, defaults to '/'
14 
15 # Email (MailProperties)
16 spring.mail.host=smtp.acme.org # mail server host
17 spring.mail.port= # mail server port
18 spring.mail.username=
19 spring.mail.password=
20 spring.mail.default-encoding=UTF-8 # encoding to use for MimeMessages
21 spring.mail.properties.*= # properties to set on the JavaMail session

 这种方式用的并不多,我们也可以通过SpringApplication.setAddCommandLineProperties(false)禁用命令行配置

Java系统属性

注意Java系统属性位置java -Dname="lsd" -jar test.jar,可以配置的属性都是一样的,优先级不同。这也没什么好讲的,都是不常用的方法。

系统环境变量

这种方式一般也不推荐,我们对系统环境变量肯定并不陌生,我们学Java肯定配置过Java_HOME,配置maven肯定也有MAVEN_Home,这些都是参数,只不过对于server.port我们需要写成SERVER_PORT,原因的话因为有些系统环境变量对.并不识别,所以规范就是用_代替.

RandomValuePropertySource

系统中用到随机数的地方,例如:

1 my.secret=${random.value}
2 my.number=${random.int}
3 my.bignumber=${random.long}
4 my.number.less.than.ten=${random.int(10)}
5 my.number.in.range=${random.int[1024,65536]}

random.int*支持value参数和,max参数,当提供max参数的时候,value就是最小值。(我还没用过)
使用配置文件--properties或者yml文件

这种应该是我们开发人员最为熟悉的方式了,因为他的简单方便,统一管理,可读性高,常常用来配置参数。

如果是properties文件,只要用过 参数名=参数值 的方式就是配置一个参数,例如:

1 name = lsd
2 password = 12345
3 server.port = 8080

如果是yml文件,方式如下:

1 name: lsd
2 password: 12345
3 server: 
4      port: 8080

这里要注意的是:①yml文件参数名后面的:后面必须加一个空格再加上参数值,具体的yml文件格式我另起一篇详细介绍

②spring会从classpath下的/config目录或者classpath的根目录查找application.properties或application.yml,并且/config优先于classpath根目录

@PropertySource

这个注解可以指定具体的属性配置文件,优先级比较低。

SpringApplication.setDefaultProperties

1 SpringApplication application = new SpringApplication(Application.class);
2 Map<String, Object> defaultMap = new HashMap<String, Object>();
3 defaultMap.put("name", "lsd");
4 //还可以是Properties对象
5 application.setDefaultProperties(defaultMap);
6 application.run(args);

其实说了这么多,我自己都没用过几种,还是习惯于使用配置文件了,但是最后还得看工作的公司用什么。属性配置好了怎么使用呢?我们一起学属性的使用方法吧!

方式一:@Value("${xxx}")

@Value注解注入属性是最简单的

方式二:@ConfigurationProperties

假设我们有一个对象配置如下:

1 test.name = lsd
2 test.password = 12345
3 test.address = ShangHai
4 test.telphone[0] = 13333333333
5 test.telphone[1] = 18888888888

那我们可以像这样注入这个对象的值:

 1 @ConfigurationProperties(prefix="test")
 2 public class Config {
 3     private String name;
 4     private String password;
 5     private String address;
 6     private List<Integer> telphone = new ArrayList<Integer>();
 7 
 8     public String getName(){
 9         return this.name;
10     }
11 
12     public String getPassword(){
13         return this.password;
14     }
15     
16     public String getAddress(){
17         return this.address;
18     }
19 
20     public List<Integer> getTelphone() {
21         return this.telphone;
22     }
23 }

SpringBoot 会根据注解@ConfigurationProperties中属性值test,在配置文件中找到test为前缀的对象,并且按参数名自动注入值,同时springboot会自动进行类型转换,但是使用List时需要自己进行list对象的初始化,不然会报错。当然,springboot不仅可以单一对象的注入,还可以嵌套属性注入。假设有如下的属性配置:

1 name=lsd
2 jdbc.username=root
3 jdbc.password=root

我们可以这样建立一个注入类:

@ConfigurationProperties
public class Config {
    private String name;
    private Jdbc jdbc;
    class Jdbc {
        private String username;
        private String password;
        public String getUsername(){
            return this.username;
        }
        public String getPassword(){
            return this.password;
        }
    }

    public Integer gePort(){
        return this.port;
    }
    public Jdbc getJdbc() {
        return this.jdbc;
    }
}

jdbc为前缀的属性都会注入到JDBC对象中。

配置文件中属性的复用

1 test.name = lsd
2 test.desc = ${test.name} is a springboot application

注意:属性的复用前提是在本属性之前已经定义过,不然会找不到引用的属性值。为了避免这种问题,我们复用属性时可以设置默认值。通过如${app.name:默认名称}方法可以设置默认值,当找不到引用的属性时,会使用默认的属性。由于${}方式会被Maven处理。如果你pom继承的spring-boot-starter-parent,Spring Boot 已经将maven-resources-plugins默认的${xxx}方式改为了@xxx@方式,例如@name@。

属性的匹配规则

假设一个对象的配置如下:

1 @Component
2 @ConfigurationProperties(prefix="person")
3 public class ConnectionSettings {
4 
5     private String firstName;
6 
7 }

那firstName可以使用的属性名有

①person.firstName,标准的驼峰式命名

②person.first-name,(-)分割方式,推荐在.properties和.yml配置文件中使用

③PERSON_FIRST_NAME,大写下划线形式,建议在系统环境变量中使用

就写这么多吧,虽然是照着前人写的文章学习的,但是也受益良多!

原文地址:https://www.cnblogs.com/timePasser-leoli/p/8416743.html