今天用到公司的工具类有个获取Spring容器bean的方法,点开看了下源码,发现只是实现类ApplicationContextAware, EmbeddedValueResolverAware两个接口
继承ApplicationContextAware接口会重写setApplicationContext方法,该方法在启动时会自动执行,前提时该类也属于IOC容器,比如有@Component注解,
执行后可以拿到框架加载的Ioc容器。
@Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringHelper.applicationContext = applicationContext; }
简单来说,这个接口就是用来获取自动初始化的ioc容器对象的;
看下源码:
package com.lyq.utils; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.EmbeddedValueResolverAware; import org.springframework.stereotype.Component; import org.springframework.util.StringValueResolver; @Component public class SpringHelper implements ApplicationContextAware, EmbeddedValueResolverAware { //静态ApplicationContext private static ApplicationContext applicationContext; private static StringValueResolver valueResolver; public SpringHelper(){} @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { /** 将框架初始化加载的ioc容器赋值给 静态ApplicationContext*/ SpringHelper.applicationContext = applicationContext; } @Override public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) { } //获取Ioc容器 public static ApplicationContext getApplicationContext(){ return applicationContext; } //通过class获取Bean public static <T> T getBean(Class<T> clazz){ return getApplicationContext().getBean(clazz); } //通过名称获取Bean public static Object getBean(String name){ return getApplicationContext().getBean(name); } //通过名称、class获取Bean public static <T> T getBean(Class<T> clazz, String name){ return getApplicationContext().getBean(name, clazz); } }