您的位置:首页 > 编程语言 > Java开发

springboot 使用属性文件,自定义常量方案

2018-04-02 09:20 776 查看
引言:常量定义在application.properties文件里面也可以;当然,用@Value 取值也可以。但是,有时候我们要自己定义一个常量文件,那怎么读取这个属性文件的值呢? 下面就贡献一下我的探索吧。
1.定义一个存放常量的properties文件


# REDIS_LOGIN_TOKENcom.login.token = tokencom.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.使用常量:  (和普通的类引用一样)
@Autowiredprivate Constant constant;
String token = CookieUtils.getCookieValue(request,constant.getToken());
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  springboot