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

本文介绍如何在SpringBoot项目中自定义常量文件并读取其值。通过定义properties文件和对应的Bean,利用@PropertySource和@ConfigurationProperties实现属性注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引言:常量定义在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());


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值