通过ApplicationContextAware回调接口,访问到Spring的应用上下文ApplicationContext

一、定义工具类如下:

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


@Component
public class SpringContextUtil implements ApplicationContextAware {

    /** Spring应用上下文 */
    private static ApplicationContext context;

    // 当Spring容器创建该类的实例时,会自动调用此方法,注入应用上下文  
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
    
    // 获取bean对象的静态方法
    public static <T> T getBean(Class<T> beanclass) {
        return context.getBean(beanclass);
    }
    
    // 可以方便地读取 application.properties 或 application.yml 中的配置项
    public static String getProperty(String key) {
        return context.getEnvironment().getProperty(key);
    }
}

二、如下读取相应配置:

String key = SpringContextUtil.getProperty("key");

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐