spring工具类 方便在非spring管理环境中获取bean

前言:

平常我们开发中,从spring ico容器中获取对象

@Autowired
private TokenService tokenService;
@Resource
private TokenService tokenService;

那么,有还有什么办法从容器获取对象呢?

ApplicationContextAware 接口

实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得ApplicationContext中的所有bean。换句话说,就是这个类可以直接获取spring配置文件中,所有有引用到的bean对象。

首先我将 tokenService对象 放到容器中:

spring工具类 方便在非spring管理环境中获取bean_第1张图片

接下里我们自己创建一个类,实现这个ApplicationContextAware接口 

package com.ruoyi.common.utils.spring;

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

/**
 * @Author Lxq
 * @Date 2020/8/31 18:00
 * @Version 1.0
 * 

* spring工具类 方便在非spring管理环境中获取bean */ @Component public final class SpringManager implements ApplicationContextAware { /** * Spring应用上下文环境 */ private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringManager.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 获取类型为requiredType的对象 * * @param clz * @return * @throws org.springframework.beans.BeansException */ public static T getBean(Class clz) throws BeansException { T result = (T) applicationContext.getBean(clz); return result; } /** * @param name * @return Class 注册对象的类型 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException */ public static Class getType(String name) throws NoSuchBeanDefinitionException { return applicationContext.getType(name); } /** * ioc容器中是否包含一个与所给名称匹配的bean定义 * * @param name * @return 存在返回true否则返回false */ public static boolean containBean(String name) { return applicationContext.containsBean(name); } }

 启动项目,测试:

spring工具类 方便在非spring管理环境中获取bean_第2张图片

 

你可能感兴趣的:(java)