SpringBoot2.x-静态类获取application.properties中自定义配置信息

文章目录

    • 获取application.properties的配置
      • 首先创建一个实现ApplicationContextAware的类
      • 获取配置
      • 测试是否可以获取

获取application.properties的配置

首先创建一个实现ApplicationContextAware的类

实现方法setApplicationContext()

package rui.zhang.crawler.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class AppConfig implements ApplicationContextAware {
    private static ApplicationContext applicationContext=null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        AppConfig.applicationContext=applicationContext;
    }

    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }
}

获取配置

package rui.zhang.crawler.utils;

import org.springframework.core.env.Environment;
import rui.zhang.crawler.config.AppConfig;

public class ConfigUtil {
    //从上下文中获取环境信息
    private static Environment environment = AppConfig.getApplicationContext().getEnvironment();

    /**
     * 根据key获取配置信息
     * @param key
     * @return
     */
    public static String getProperties(String key){
        return environment.getProperty(key);
    }

}

测试是否可以获取

package rui.zhang.crawler;

import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import rui.zhang.crawler.utils.ConfigUtil;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = CrawlerApplication.class)
@WebAppConfiguration
public class ConfigTest {
    @org.junit.jupiter.api.Test
    public void aQiYi(){
        String info= ConfigUtil.getProperties("info");
        System.out.println(info);
    }
}

你可能感兴趣的:(SpringBoot,spring)