美文网首页
Springboot 通过类路径从ioc容器中获得Bean

Springboot 通过类路径从ioc容器中获得Bean

作者: 往后余生9375 | 来源:发表于2022-04-13 17:49 被阅读0次

    SpringUtils

    public class SpringUtils {
    
        private static boolean supportSpringBean = false;
    
        private static ApplicationContext context;
    
        public static void inject(ApplicationContext ctx) {
            context = ctx;
            supportSpringBean = true;
        }
    
        public static boolean supportSpringBean() {
            return supportSpringBean;
        }
    
        public static <T> T getBean(Class<T> clz) {
            return context.getBean(clz);
        }
    
        @SuppressWarnings("unchecked")
        public static <T> T getBean(String className) throws Exception {
    
            // 1. ClassLoader 存在,则直接使用 clz 加载
            ClassLoader classLoader = context.getClassLoader();
            if (classLoader != null) {
                return (T) context.getBean(classLoader.loadClass(className));
            }
            // 2. ClassLoader 不存在(系统类加载器不可见),尝试用类名称小写加载
            String[] split = className.split("\\.");
            String beanName = split[split.length - 1];
            // 小写转大写
            char[] cs = beanName.toCharArray();
            cs[0] += 32;
            String beanName0 = String.valueOf(cs);
            return (T) context.getBean(beanName0);
        }
    }
    
    

    Application

    @SpringBootApplication
    public class DllUtilsApplication implements ApplicationContextAware {
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            SpringUtils.inject(applicationContext);
        }
    
        public static void main(String[] args) {
            SpringApplication.run(DllUtilsApplication.class, args);
        }
    
    }
    

    使用

    // Test使用@Component注解
    Test test = SpringUtils.getBean("com.example.dllutils.Test");
    test.print();
    

    相关文章

      网友评论

          本文标题:Springboot 通过类路径从ioc容器中获得Bean

          本文链接:https://www.haomeiwen.com/subject/ywbasrtx.html