首页 > 其他分享 >Spring Boot 属性配置和使用

Spring Boot 属性配置和使用

时间:2022-12-20 23:05:38浏览次数:56  
标签:name Spring Boot application public 属性

 

3.2.2.2 Java Config使用方式

假设我有一个TestJavaConfigBean,通过Java Config的方式还可以使用@Value的方式注入:

public class TestJavaConfigBean {
@Value("${timeout:100}")
private int timeout;
private int batch;

@Value("${batch:200}")
public void setBatch(int batch) {
this.batch = batch;
}

public int getTimeout() {
return timeout;
}

public int getBatch() {
return batch;
}
}

 

在Configuration类中按照下面的方式使用(假设应用默认的application namespace中有​​timeout​​​和​​batch​​的配置项):

@Configuration
@EnableApolloConfig
public class AppConfig {
@Bean
public TestJavaConfigBean javaConfigBean() {
return new TestJavaConfigBean();
}
}

 

3.2.2.3 ConfigurationProperties使用方式

Spring Boot提供了​​@ConfigurationProperties​​把配置注入到bean对象中。

Apollo也支持这种方式,下面的例子会把​​redis.cache.expireSeconds​​​和​​redis.cache.commandTimeout​​​分别注入到SampleRedisConfig的​​expireSeconds​​​和​​commandTimeout​​字段中。

@ConfigurationProperties(prefix = "redis.cache")
public class SampleRedisConfig {
private int expireSeconds;
private int commandTimeout;

public void setExpireSeconds(int expireSeconds) {
this.expireSeconds = expireSeconds;
}

public void setCommandTimeout(int commandTimeout) {
this.commandTimeout = commandTimeout;
}
}

 

在Configuration类中按照下面的方式使用(假设应用默认的application namespace中有​​redis.cache.expireSeconds​​​和​​redis.cache.commandTimeout​​的配置项):

@Configuration
@EnableApolloConfig
public class AppConfig {
@Bean
public SampleRedisConfig sampleRedisConfig() {
return new SampleRedisConfig();
}
}

 

​https://github.com/ctripcorp/apollo/wiki/Java%E5%AE%A2%E6%88%B7%E7%AB%AF%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97​​​



Spring boot中yml配置文件的缩进是按前面字母的,不是以后面":"为参照物的

注解是javaSE5中的重要的语言变化之一。
它们可以提供用来完整地描述程序所需的信息,而这些信息是无法用java来表达的。
因此注解可以用来生成描述文件,甚至或是新的类定义,并且有助于减轻编写”样板“代码的负担。
通过使用注解,可以将这些元素数据保存在Java源代码中,并利用annotation API为自己的注解构造处理工具,

同时,注解的优点还包括:更加干净易读的代码以及编译期类型检查等。

注解中定义了名为value的元素,并且在应用该注解的时候,如果该元素是唯一需要赋值的一个元素,那么无需使用名-值对的这种语法,而只需在括号内给出value元素所需的值即可。这可以应用于任何合法类型的元素。
当然了,这也限制了程序员必须将此元素命名为value

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

Spring Boot 支持多种外部配置方式

这些方式优先级如下:

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

命令行参数

通过​​java -jar app.jar --name="Spring" --server.port=9090​方式来传递参数【-- 传参的方式,只能在java -jar xxx.jar后面】。

参数用​​--xxx=xxx​​的形式传递。

可以使用的参数可以是我们自己定义的,也可以是Spring Boot中默认的参数。

很多人可能会关心如web端口如何配置这样的问题,这些都是Spring Boot中提供的参数,部分可用参数如下:

# LOGGING
logging.path=/var/logs
logging.file=myapp.log
logging.config= # location of config file (default classpath:logback.xml for logback)
logging.level.*= # levels for loggers, e.g. "logging.level.org.springframework=DEBUG" (TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF)

# EMBEDDED SERVER CONFIGURATION (ServerProperties)
server.port=8080
server.address= # bind to a specific NIC
server.session-timeout= # session timeout in seconds
server.context-parameters.*= # Servlet context init parameters, e.g. server.context-parameters.a=alpha
server.context-path= # the context path, defaults to '/'
server.servlet-path= # the servlet path, defaults to '/'

更多常见的应用属性请浏览​​这里​

注意:命令行参数在​​app.jar​​的后面!

可以通过​​SpringApplication.setAddCommandLineProperties(false)​​禁用命令行配置。

Java系统属性

注意Java系统属性位置​​java -Dname="isea533" -jar app.jar​​,可以配置的属性都是一样的,优先级不同。

例如​​java -Dname="isea533" -jar app.jar --name="Spring!"​​​中​​name​​​值为​​Spring!​

操作系统环境变量

配置过JAVA_HOME的应该都了解这一个。

这里需要注意的地方,有些OS可以不支持使用​​.​​​这种名字,如​​server.port​​​,这种情况可以使用​​SERVER_PORT​​来配置。

具体名字如何匹配,看本文后面。

RandomValuePropertySource

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

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

​random.int*​​​支持​​value​​​参数和​​,max​​​参数,当提供​​max​​​参数的时候,​​value​​就是最小值。

应用配置文件(.properties或.yml)

在配置文件中直接写:

name=Isea533
server.port=8080

​.yml​​格式的配置文件如:

name: Isea533
server:
port: 8080

当有前缀的情况下,使用​​.yml​​​格式的配置文件更简单。关于​​.yml​​​配置文件用法请看​​这里​

注意:使用​​.yml​​​时,属性名的值和冒号中间必须有空格,如​​name: Isea533​​​正确,​​name:Isea533​​就是错的。

属性配置文件的位置

spring会从classpath下的​​/config​​​目录或者classpath的根目录查找​​application.properties​​​或​​application.yml​​。

​/config​​​优先于​​classpath根目录​

@PropertySource

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

SpringApplication.setDefaultProperties

例如:

SpringApplication application = new SpringApplication(Application.class);
Map<String, Object> defaultMap = new HashMap<String, Object>();
defaultMap.put("name", "Isea-Blog");
//还可以是Properties对象
application.setDefaultProperties(defaultMap);
application.run(args);

应用(使用)属性

@Value(“${xxx}”)

这种方式是最简单的,通过​​@Value​​注解可以将属性值注入进来。

@ConfigurationProperties

Spring Boot 可以方便的将属性注入到一个配置对象中。例如:

my.name=Isea533
my.port=8080
my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com

对应对象:

@ConfigurationProperties(prefix="my")
public class Config {
private String name;
private Integer port;
private List<String> servers = new ArrayList<String>();

public String geName(){
return this.name;
}

public Integer gePort(){
return this.port;
}
public List<String> getServers() {
return this.servers;
}
}

Spring Boot 会自动将​​prefix="my"​​​前缀为​​my​​的属性注入进来。

Spring Boot 会自动转换类型,当使用​​List​​​的时候需要注意在配置中对​​List​​进行初始化!

Spring Boot 还支持嵌套属性注入,例如:

name=isea533
jdbc.username=root
jdbc.password=root
...

对应的配置类:

@ConfigurationProperties
public class Config {
private String name;
private Jdbc jdbc;
class Jdbc {
private String username;
private String password;
//getter...
}

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

​jdbc​​​开头的属性都会注入到​​Jdbc​​对象中。

在@Bean方法上使用@ConfigurationProperties

例如:

@ConfigurationProperties(prefix = "foo")
@Bean
public FooComponent fooComponent() {
...
}

Spring Boot 会将​​foo​​​开头的属性按照名字匹配注入到​​FooComponent​​对象中。

属性占位符

例如:

app.name=MyApp
app.description=${app.name} is a Spring Boot application

可以在配置文件中引用前面配置过的属性(优先级前面配置过的这里都能用)。

通过如​​${app.name:默认名称}​​方法还可以设置默认值,当找不到引用的属性时,会使用默认的属性。

由于​​${}​​​方式会被Maven处理。如果你pom继承的​​spring-boot-starter-parent​​​,Spring Boot 已经将​​maven-resources-plugins​​​默认的​​${}​​​方式改为了​​@ @​​​方式,例如​​@name@​​。

如果你是引入的Spring Boot,你可以修改使用​​其他的分隔符​

通过属性占位符还能缩短命令参数

例如修改web默认端口需要使用​​--server.port=9090​​方式,如果在配置中写上:

server.port=${port:8080}

那么就可以使用更短的​​--port=9090​​​,当不提供该参数的时候使用默认值​​8080​​。

属性名匹配规则

例如有如下配置对象:

@Component
@ConfigurationProperties(prefix="person")
public class ConnectionSettings {

private String firstName;

}

​firstName​​可以使用的属性名如下:

  1. ​person.firstName​​,标准的驼峰式命名
  2. ​person.first-name​​​,虚线(​​-​​​)分割方式,推荐在​​.properties​​​和​​.yml​​配置文件中使用
  3. ​PERSON_FIRST_NAME​​,大写下划线形式,建议在系统环境变量中使用

属性验证

可以使用​​JSR-303​​注解进行验证,例如:

@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {

@NotNull
private InetAddress remoteAddress;

// ... getters and setters

}

最后

以上是Spring Boot 属性配置和使用的内容,有些不全面的地方或者读者有更多疑问,可以查看​​Spring Boot完整文档​​​ 或 ​​Externalized Configuration​​。

关于Spring Boot更多的内容可以继续关注本博客。

Spring Boot 系列

由于我博客Spring Boot 系列文章还不够多,所以暂时不打算创建专栏,如果再多几篇我就建专栏。

  1. ​​Spring Boot 入门​​
  2. ​​Spring Boot 属性配置和使用​​
  3. ​​Spring Boot 集成MyBatis​​
  4. ​​Spring Boot 静态资源处理​​


标签:name,Spring,Boot,application,public,属性
From: https://blog.51cto.com/u_15147537/5956959

相关文章

  • org.springframework.util.Assert
    使用assert的好处就是比较简介,不用加trycatch就可以附加一些预期的提示信息,方便定位问题importorg.springframework.util.Assert;publicclassDemo{publicstaticv......
  • Error creating bean with name 'org.springframework.validation.beanvalidation.Loc
    Errorcreatingbeanwithname‘org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0’Causedby:javax.validation.ValidationException:Unab......
  • spring mvc+ELK从头开始搭建日志平台
    springmvc+ELK从头开始搭建日志平台最近由于之前协助前公司做了点力所能及的事情,居然收到了一份贵重的端午礼物,是给我女儿的一个乐高积木,整个有7大包物件,我花了接近一天的......
  • Spring AOP
    AOP面向切面编程,相对于OOP面向对象编程。​​spring​​ AOP存在的目的是为了解耦。AOP可以让一组类共享相同的行为。在OOP中只能通过继承类和实现接口,来使代码的耦合度增......
  • Spring Boot「15」统一异常处理
    持续创作,加速成长!这是我参与「掘金日新计划·10月更文挑战」的第15天,点击查看活动详情今天我们将一块学习下SpringMVC中实现统一异常处理的几种方式。总得来说,统一......
  • Spring MVC 拦截器实现登录拦截以及多拦截器的配置执行详解
    持续创作,加速成长!这是我参与「掘金日新计划·10月更文挑战」的第25天,点击查看活动详情前言上一篇文章我们简单了解并完成了SpringMVC拦截器的入门案例,这一篇文章,我们......
  • 构成 Spring Web 服务的各种组件(二)
    6.在客户端上使用SpringWeb服务Spring-WS提供了一个客户端Web服务API,允许对Web服务进行一致的XML驱动访问。它还迎合了编组程序和取消编组程序的使用,以便服务层代码可以......
  • SpringBoot - Yaml语法
    测试用到的类:类的属性必须重写Get与Set方法不管属性是私有的还是公共的,必须重写Get与Set方法@Component@ConfigurationProperties(prefix="student")publicclass......
  • Spring源码编译
    资料参考地址1:Spring源码编译准备环境配置JDK8(与Spring5的兼容性最好)spring:5.2.0release下载Spring源码直接去官方的github库下载,https://github.com/spring......
  • Spring batch
    1.springbatch--批处理框架2.结构:Job>Flow>Step>Chunk>readprocesswrite2.1基本概念:SpringBatch运行基本单位是一个job,一个job就做一件批处理事情。......