springboot配置文件变量转换java类静态常量

在项目下的application.properties文件中存在如下配置

# pagehelper 分页
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql

那么我们现在想通过常量类直接获取,怎么操作。

首先配置依赖加入

spring-boot-configuration-processor
<!--配置文件处理器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

其次给常量副值。这里定义的常量类ConfConstants 

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Desc : 配置文件变量变常量
 * @author : Chenweixian 陈惟鲜
 * @Date : 2022年8月24日 下午2:54:37
 */
@Component
public class ConfConstants implements InitializingBean{
//    #数据库类型取不到默认给mysql
    @Value("${pagehelper.helperDialect:mysql}")
    public String pagehelper_helperdialect;
    
    /**#秘钥串*/
    public static String PAGEHELPER_HELPERDIALECT;
    
    @Override
    public void afterPropertiesSet() throws Exception {
        PAGEHELPER_HELPERDIALECT = this.pagehelper_helperdialect;
    }
}

 

最后测试:

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

import com.ccjr.test.BaseTest;

public class StringRemote extends BaseTest{
    


    @Test
    public void confTest() throws Exception {
        System.out.println(ConfConstants.PAGEHELPER_HELPERDIALECT);
    }
}

测试发现,能正确输出配置的值

posted on 2022-08-24 15:05  陈惟鲜的博客  阅读(600)  评论(0编辑  收藏  举报

导航