美文网首页
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

    SpringUtils Application 使用

  • spring学习3(基本XML配置)

    配置Bean 基本配置 class:bean的全类名,通过反射方式在ioc容器中创建bean的实例 id:标识容器...

  • SpringIOC

    配置bean class: bean 的全类名,通过反射的方式在IOC容器中创建Bean,所以要求Bean中必须有...

  • Java Spring-配置Bean

    配置bean,class:bean的全类名,通过反射的方式在IOC容器中创建Bean,所以要求Bean中必须有无参...

  • spring国际化

    Springboot 多语spring多语的使用,需要将名称为messageSource的bean放到ioc容器中...

  • Springboot解析spel表达式

    调用springboot解析spel表达式,可以通过表达式调用ioc容器中的bean或者解析自定义的参数 appl...

  • SpringBoot进阶学习上篇

    1、SpringBoot核心概念 1.1Spring优缺点 Spring优点:通过IOC容器统一管理Bean大大简...

  • Spring生命周期管理

    一、Bean的解析加载 IOC容器启动 IOC容器通过applicationContext.refresh()加载...

  • [Spring]Bean与BeanDefinition

    IOC容器 IOC容器主要的职责有: Spring IOC 可以从配置文件或者注解中根据每个Bean的定义,将这些...

  • 方法注入

    先通过@Bean将User的Bean生成并且放入到IOC容器中 @AutoWired和@Resource修饰方法,...

网友评论

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

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