zoukankan      html  css  js  c++  java
  • 普通类获取Bean和获取配置值

    Spring中的Aware

    • Spring框架中提供了许多实现了Aware接口的类,这些类主要是为了辅助Spring访问容器中的数据,比如BeanNameAware,这个类能够在Spring容器加载的过程中将Bean的名字(id)赋值给变量。

    ApplicationContextAware

    实现该类可以获取到ApplicationContext,通过ApplicationContext就可以获取到Bean

    @Component
    public class SpringUtil implements ApplicationContextAware {
    
        private static ApplicationContext applicationContext;
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            if(SpringUtil.applicationContext == null){
                SpringUtil.applicationContext = applicationContext;
            }
        }
    
        public static ApplicationContext getApplicationContext(){
            return applicationContext;
        }
    
        public static Object getBean(String name){
            return getApplicationContext().getBean(name);
        }
    
        public static <T> T getBean(Class<T> clazz){
            return getApplicationContext().getBean(clazz);
        }
    
        public static <T> T getBean(String name,Class<T> clazz){
            return getApplicationContext().getBean(name, clazz);
        }
    
    }
    

    EmbeddedValueResolverAware

    通过实现该类就可以获取到spring核心配置文件中的配置值(application.yml,application.properties)。

    但是需要通过${key}获取

    /**
     * 非spring容器管理的类可以通过此类获取配置值
     */
    @Component
    public class PropertiesUtil implements EmbeddedValueResolverAware {
    
        private static StringValueResolver resolver;
    
        @Override
        public void setEmbeddedValueResolver(StringValueResolver resolver) {
            PropertiesUtil.resolver = resolver;
        }
    
        public static String getPropertiesValue(String key){
            return resolver.resolveStringValue(key);
        }
    }
    

    举例:

    String name = PropertiesUtil.getPropertiesValue("${spring.application.name}")
    
  • 相关阅读:
    网站跨站点单点登录实现--cookie
    sql order by 排序多个字段
    JAVA字符串格式化-String.format()的使用
    Cent OS 常用配置命令
    键盘事件keydown、keypress、keyup随笔整理总结
    Chrome 开发者工具使用技巧
    JS打开新窗口防止被浏览器阻止的方法[转]
    javaBean与map类型相互转换
    【转载】 自动化机器学习(AutoML)之自动贝叶斯调参
    国内还不错的量化交易平台
  • 原文地址:https://www.cnblogs.com/wwjj4811/p/14107010.html
Copyright © 2011-2022 走看看