我们知道如果我们要在一个类使用
 spring提供的bean对象,我们需要把这个类注入到spring容器中,交给spring容器进行管理,但是在实际当中,我们往往会碰到在一个普通的Java类中,想直接使用spring提供的其他对象或者说有一些不需要交给spring管理,但是需要用到spring里的一些对象。如果这是spring框架的独立应用程序,我们通过
 

ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
ac.getBean("beanId"); 

 这样的方式就可以很轻易的获取我们所需要的对象。

 但是往往我们所做的都是Web Application,这时我们启动spring容器是通过在web.xml文件中配置,这样就不适合使用上面的方式在普通类去获取对象了,因为这样做就相当于加载了两次spring容器,而我们想是否可以通过在启动web服务器的时候,就把Application放在某一个类中,我们通过这个类在获取,这样就可以在普通类获取spring bean对象了。不多说,看实例!

1.在Spring Boot可以扫描的包下

写的工具类为SpringUtil,实现ApplicationContextAware接口,并加入Component注解,让spring扫描到该bean

因为我们其实是想要的是ApplicationContext,这里就能获取Bean的管理容器

之前通过看源码,得知在Bean的初始化的过程中,有一个步骤是执行实现了Aware接口的方法

实现了对应的Aware接口,我们就能拿到对应的实例。

如果想看spring启动的源码可看如下链接

https://blog.csdn.net/qq_29235677/article/details/118458990


这里提供了3种方法,实现相关的bean的获取,

  • 方法1:bean的名称
  • 方法2:class字节码对象
  • 方法3:bean的名字+class字节码对象 
@Slf4j
@Component
public class BeanUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;


    /**
     * Spring容器会在创建该Bean之后,自动调用该Bean的setApplicationContext方法
     *
     * @param applicationContext
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        if (BeanUtils.applicationContext == null) {
            BeanUtils.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);
    }

}

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐