一、首先我们看一下ApplicationContextAware接口的源码
package org.springframework.context;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.Aware;
public interface ApplicationContextAware extends Aware {
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
package org.springframework.beans.factory;
public abstract interface Aware {
}
1.ApplicationContext是上下文的意思,我们编写的类实现ApplicationContextAware接口就可以获取Spring容器的应用上下文环境。当容器加载Spring的配置文件时会自动调用ApplicationContextAware的setApplicationContext()方法自动获取ApplicationContext对象,利用ApplicationContext可以得到我们想要的各种上下文,比如最常用的获取Spring实例,接下来会有实例。
2.有人可能会问Aware接口什么都没做为什么还用集成它呢?因为不仅ApplicationContextAware集成了它,其他的接口也同样集成了Aware接口,如:BeanNameAware、BeanFactoryAware和ResourceLoaderAware等。因此集成Aware接口的目的主要是实现java多态的特性。
二、SpringContextHolder实现ApplicationContextAware接口
testwebapp.com.wangzuojia.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <O> O getBean(String name, Class<O> requiredType) {
return applicationContext.getBean(name, requiredType);
}
public static <O> O getBean(Class<O> requiredType) {
return applicationContext.getBean(requiredType);
}
public static <O> String[] getBeanNamesForType(Class<O> requiredType) {
return applicationContext.getBeanNamesForType(requiredType);
}
/**
* 实现ApplicationContextAware的setApplicationContext方法,设置上下文环境
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
三、实例
public class GenerationApplicationNoUtil {
/**
* 获取下一个流水号,获取时根据查询条件判断,如果没有则新加一条记录,否则加1
* @throws Exception
*/
public static String getMaxSerialNumber(String branchcode, String year,
String orgcode, String serialtype, String hmlb, String productcode, int limitLength, String padStr) {
......
//此处使用ApplicationContextAware获取Spring Bean
TCounterService tCounterService = SpringContextHolder
.getBean(TCounterService.class);
String simpleCode = tCounterService.getMaxSerialNumber(branchcode, year,
orgcode, serialtype, hmlb, productcode);
return simpleCode;
} catch (Exception e) {
logger.error("获取流水号报错:" + ExceptionUtil.getErrorMsg(e), e);
throw new BusinessException("获取流水号报错:"
+ ExceptionUtil.getErrorMsg(e), e);
} finally {
// 还原为之前正在使用的dbtype
if (oldDbtype != null) {
DataSourceContextHolder.setDataSource(oldDbtype);
}
}
}
}