引言:常量定义在application.properties文件里面也可以;当然,用@Value 取值也可以。但是,有时候我们要自己定义一个常量文件,那怎么读取这个属性文件的值呢? 下面就贡献一下我的探索吧。
1.定义一个存放常量的properties文件
# REDIS_LOGIN_TOKEN
com.login.token = token
com.login.tokenExpire = 18000
2.定义一个存放常量的bean
package com.constant ;
import org.springframework.beans.factory.annotation. Value ;
import org.springframework.boot.context.properties. ConfigurationProperties ;
import org.springframework.context.annotation. Configuration ;
import org.springframework.context.annotation. PropertySource ;
@Configuration
@ConfigurationProperties ( prefix = “com.login” )
@PropertySource ( “classpath:constant.properties” )
public class Constant {
private String token ;
private Integer tokenExpire ;
public Integer getTokenExpire () {
return tokenExpire ;
}
public void setTokenExpire (Integer tokenExpire) {
this . tokenExpire = tokenExpire ;
}
public String getToken () {
return token ;
}
public void setToken (String token) {
this . token = token ;
}
}
3.在app.java里注册声明给spring,这个bean是作为常量使用
@EnableConfigurationProperties ({Constant. class })
4.使用常量: (和普通的类引用一样)
@Autowired
private Constant constant ;
String token = CookieUtils. getCookieValue (request , constant .getToken()) ;