获取Spring IOC容器中bean对象

Spring常用的开发框架有SpringMVC和SpringBoot,很多时候后都是用@Component,@Service等注解类,或者在Spring配置文件中声明bean,使用的时候,在通过 @Resource或者 @Resource注解获取对象,但在某些情况下,无法使用自动注解获取对象,这个时候就需要从IOC容器中获取bean对象。

创建获取bean对象工具类 使用@Component注解
/**
 * @author :xiao@case
 * @date : 2019/7/19 15:19
 * @description:获取Spring的IOC容器
 * @version: 1.0$
 */
@Component
public class ApplicationContextConfig implements ApplicationContextAware {
          
   
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
          
   
        /**
         *获取Spring的IOC容器ApplicationContext
         * @author xiao@case
         * @date 2019/7/30 9:59
         */
        if (ApplicationContextConfig.getContext() == null) {
          
   
            ApplicationContextConfig.setContext(applicationContext);
        }
    }

    public static ApplicationContext getContext() {
          
   
        return context;
    }

    public static void setContext(ApplicationContext context) {
          
   
        ApplicationContextConfig.context = context;
    }

    /**
     * 通过name获取 Bean.
     *
     * @author xiao@case
     * @date 2019/7/19 15:22
     */
    public static Object getBean(String name) {
          
   
        return getContext().getBean(name);
    }

    /**
     * 通过class获取Bean.
     *
     * @author xiao@case
     * @date 2019/7/19 15:23
     */
    public static <T> T getBean(Class<T> clazz) {
          
   
        return getContext().getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @author xiao@case
     * @date 2019/7/19 15:23
     */
    public static <T> T getBean(String name, Class<T> clazz) {
          
   
        return getContext().getBean(name, clazz);
    }
}
如果使用SpringMVC框架,在配置文件中声明该工具类
<!--声明bean对象-->
<bean id="applicationContextConfig" class="com.sydtech.itmc.config.ApplicationContextConfig"/>
如果是SpringBoot框架,有两种方式声明ApplicationContextConfig类到IOC容器中 1、定义ApplicationContextConfig类的包路径能被Springboot扫码到 2、使用@Bean注解的方式声明ApplicationContextConfig类 @Bean可理解为用spring的时候xml里面的bean标签
/**
 * @description:Spring 容器配置
 * @version: 1, 0$
 */
@Configuration
public class AppConfiguration {
          
   
    @Bean
    @Scope("prototype")
    public ApplicationContextConfig applicationContextConfig() {
          
   
        return new ApplicationContextConfig();
    }
}
使用时直接调用ApplicationContextConfig 类中的静态方法getBean
//获取线程池对象
threadPoolTaskExecutor = ApplicationContextConfig.getBean(ThreadPoolTaskExecutor.class);

写在最后

人这一生也没有多少时间可以挥霍, 踏实一点,务实一点,专注一点 做自己想做的事, 生活都是小Case!

经验分享 程序员 微信小程序 职场和发展