如图,我想写一个关于 环境的工具类。(dev/stage/pro) 。
已知:spring中@Autowired  Environment env注解可以注入当前环境。
所以ApplicationContext中存在env的bean。
,EnvironmentHelper
类里实现 获取dev. yml,pro. yml配置 的 信static息方法
思路是:A我导pplicationContext中Enviroment envm
但结果显示 似在静态方法不能使env的javabean用。
这种问题怎么解决备注:ContextUtils自定义的工具类,获取ApplicationContext容器。?

解决方案 »

  1.   

    ,难道这种想法是错的static方法内部不能使用bean?还是说 我姿势不对,要换一种写法?
      

  2.   

    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.stereotype.Component;/**
     * SpringUtils.java
     * @author songb
     */
    @Component
    public class SpringUtils implements ApplicationContextAware {
        private static ApplicationContext applicationContext;    @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            if(SpringUtils.applicationContext == null) {
                SpringUtils.applicationContext = applicationContext;
            }
        }    //获取applicationContext
        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }    //通过name获取 Bean.
        public static Object getBean(String name){
            return getApplicationContext().getBean(name);
        }    //通过class获取Bean.
        public static <T> T getBean(Class<T> clazz){
            return getApplicationContext().getBean(clazz);
        }    //通过name,以及Clazz返回指定的Bean
        public static <T> T getBean(String name,Class<T> clazz){
            return getApplicationContext().getBean(name, clazz);
        }
    }
      

  3.   

    setApplicationContext第一次装载的入口,不需要写吗。直接使用这个类?