0
点赞
收藏
分享

微信扫一扫

获取配置类中的JavaBean对象

boomwu 2022-04-29 阅读 71
java
某一个配置类

@Configuration
public class EhcacheConfig {

    @Bean
    public EhCacheManagerFactoryBean cacheManagerFactoryBean(){
        EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
        ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
        ehCacheManagerFactoryBean.setShared(true);
        return  ehCacheManagerFactoryBean;
    }

    @Bean
    public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean){
        return  new EhCacheCacheManager(bean.getObject());
    }
}




获取上面定义的 EhCacheManagerFactoryBean 类

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 从容器中获取bean工具类
 * 
 * */
@Component
public class ApplicationContextUtils  implements ApplicationContextAware {

    private static ApplicationContext  applicationContext = null ;

    /**
     * 获取上下文对象
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 通过对象在容器中的名称获取对象
     *
     * @param beanName
     * @param <T>
     * @return
     */
    public static <T> T getBean(String beanName) {
        return (T) applicationContext.getBean(beanName);
    }


    /**
     * 通过class类型获取容器中的对象
     *
     * @param beanClass
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> beanClass) {
        return (T) applicationContext.getBean(beanClass);
    }

   

    /**
     * spring启动时会自动执行该方法
     * */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            ApplicationContextUtils.applicationContext = applicationContext;
    }
}
举报

相关推荐

0 条评论