简体   繁体   中英

Put value into application.yaml and use Runtime

I have Spring boot application. I want to put the some values as read timeout, debug mode in yaml file and then read them from java code.

application.yaml :

spring:
  jpa:
      database-platform: org.hibernate.dialect.PostgreSQLDialect
      hibernate:
        ddl-auto: update
      show-sql: false


  datasource:
      url: jdbc:postgresql://localhost:5432/database_name
      username: database_username
      password: database_password


  http:
      multipart:
         maxFileSize: 15Mb
         maxRequestSize: 15Mb

server:
      port: 8585
      contextPath: /

You can do this using the @Value annotation provided by spring framework.

Here is the example:

api:
   values:
      socket-timout: 20

And in your java code you can get the value of socket-timout using the below code.

@Value("${api.values.socket-timeout}")
private Integer socketTimeout;

It will it will automatically be populated with value 20 . You can not do this for the static variables. To achieve this for the static variables, you can use the following code.

public static Integer mySocketTimeout;

@Value("${api.values.socket-timeout}")
public void setSocketTimeout(Integer socketTime){
   mySocketTimeout = socketTime;
}

By setting the the value of static variable via non-static setter method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM