欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Springboot项目中普通类直接调用注解类

程序员文章站 2022-05-23 12:46:58
...

1.定义一个普通类ApplicationContextUtil.java

public class ApplicationContextUtil{
    private static ApplicationContext applicationContext = null;

    public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (ApplicationContextUtil.applicationContext == null) {
            ApplicationContextUtil.applicationContext = applicationContext;
        }
    }
    //获取applicationContext

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    //通过name获取 Bean.

    public static Object getBean(String name) {

        return getApplicationContext().getBean(name);

    }

    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}

2.在Application启动类中调用setApplicationContext将ApplicationContext设置

@SpringBootApplication
@Import(DynamicDataSourceRegister.class)
public class Storm0810Application {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Storm0810Application.class, args);
        ApplicationContextUtil.setApplicationContext(ctx);
        PersonTopology.run();
    }
}

3.调用即可

ApplicationContextUtil.getBean(BasePersonService.class);
相关标签: ApplicationContext