基于Spring的ApplicationContext获取方式

这里主要讲解基于实际开发中获取Spring上下文的方式,区别于通过加载xml的方式(ClassPathXmlApplicationContext()和FileSystemXmlApplicationContext())。

原因:在实际Web项目启动时,Web服务器就会初始化加载Spring容器,如果在程序运行期间,再次通过加载XMl的方式获取,相当于重复加载,无疑是非常耗时的,其次我们在开发中获取ApplicationContext大多是为了抽成Util类或者getBean的Static方法。



类似于加载XML的方式我们大多用在测试环境中,在系统不启动的情况下,我们手动初始化Spring容器来获取到上下文对象。


第一种:

//第一种 是目标Bean继承ApplicationContextAware接口,实现setApplicationContext方法
		applicationContext.getBean("myBean2",MyBean2.class).getApplicationContext();

package com.harry.spring4.demo2;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class MyBean2 implements ApplicationContextAware {
	private ApplicationContext applicationContext;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
	
	public void getApplicationContext(){
		System.out.println("MyBean2: " + applicationContext.getClass());
	}
	
}



实现思路: ApplicationContextAware的实现是基于BeanPostProcessor接口,BeanPostProcessor是Spring容器Bean的后置处理器,即每个Bean在容器中装配实例化前,都会调用BeanPostProcessor的postProcessBeforeInitialization和postProcessAfterInitialization方法。

Spring源码:
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		// Tell the internal bean factory to use the context's class loader etc.
		beanFactory.setBeanClassLoader(getClassLoader());
		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

		// Configure the bean factory with context callbacks.
		beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

ApplicationContextAwareProcessor实现BeanPostProcessorj接口:

class ApplicationContextAwareProcessor implements BeanPostProcessor {

	private final ConfigurableApplicationContext applicationContext;

	private final StringValueResolver embeddedValueResolver;


	/**
	 * Create a new ApplicationContextAwareProcessor for the given context.
	 */
	public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
		this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
	}

核心方法:
@Override
	public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
		AccessControlContext acc = null;

		if (System.getSecurityManager() != null &&
				(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
						bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
						bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
			acc = this.applicationContext.getBeanFactory().getAccessControlContext();
		}

		if (acc != null) {
			AccessController.doPrivileged(new PrivilegedAction<Object>() {
				@Override
				public Object run() {
					invokeAwareInterfaces(bean);
					return null;
				}
			}, acc);
		}
		else {
			invokeAwareInterfaces(bean);
		}

		return bean;
	}

	private void invokeAwareInterfaces(Object bean) {
		if (bean instanceof Aware) {
			if (bean instanceof EnvironmentAware) {
				((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
			}
			if (bean instanceof EmbeddedValueResolverAware) {
				((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
			}
			if (bean instanceof ResourceLoaderAware) {
				((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
			}
			if (bean instanceof ApplicationEventPublisherAware) {
				((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
			}
			if (bean instanceof MessageSourceAware) {
				((MessageSourceAware) bean).setMessageSource(this.applicationContext);
			}
			if (bean instanceof ApplicationContextAware) {
				((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
			}
		}
	}

注: Spring在创建BeanFactory时的prepareBeanFactory方法中添加一个BeanPostProcessor的实现类ApplicationContextAwareProcessor,这样在每个Bean实例化时都会执行postProcessBeforeInitialization方法,在postProcessBeforeInitialization方法中可以看出他会去判断如果Bean是ApplicationContextAware的实例,则将当前applicationContext容器设置进去,类似于暴露一个钩子方法setApplicationContext(this.applicationContext),供我们去实现,这样就能拿到运行环境中的applicationContext了



第二种

package com.harry.spring4.demo2;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class MyBean3{
	private ApplicationContext applicationContext;
	
	public MyBean3(ApplicationContext applicationContext){
		this.applicationContext = applicationContext;
	}
	
	public void getApplicationContext(){
		System.out.println("MyBean3: " + applicationContext.getClass());
	}
	
}


实现思路: 基于Spring4.x的新特性,在实例化目标Bean时,对需要参数的构造方法,Spring会自动去匹配当前容器中已经装配好的参数对象进行传入,类似于传入applicationContext

注意: 这种方式,实例化Bean的构造方法只能有一个,如果有多个他会默认调用无参的构造方法,如果没有无参的构造方法,在初始化的时候会报错误,提示不知以哪种构造方法实例化对象,同时构造方法的参数必须都要在Spring容器中已经装配




最后:在实际开发中,通常使用第一种方式直接通过接口的实现方法进行获取,第二种方式Spring容器还有个参数匹配注入的过程,同时相比较与第二种,第一种的实现方式代码看起来更优雅! ^_^


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值