Spring上下文( ApplicationContext)
2019-04-25 本文已影响0人
return997
如果说BeanFactory是Spring的心脏,那么ApplicationContext就是完整的身躯了。ApplicationContext由BeanFactory派生而来,提供了更多面向实际应用的功能。
实现ApplicationContextAware接口
package com.permission.common;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @version:1.0.0
* @author: lironghong
* @date: 2019/4/21 21:04
* @description: ApplicationContext获取上下文
*/
@Component("ApplicationContextHelper")
public class ApplicationContextHelper implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T popBean(Class<T> tClass) {
if (context == null) {
return null;
}
return context.getBean(tClass);
}
public static <T> T popBean(String name, Class<T> tClass) {
if (context == null) {
return null;
}
return context.getBean(name,tClass);
}
}
配置被spring管理(spring-servlet.xml)
<bean class="com.permission.common.ApplicationContextHelper" lazy-init="false"></bean>
测试
@RequestMapping("/validator.json")
@ResponseBody
public JsonData validator(TestVo vo) throws ParamException {
log.info("validator");
SysAclMapper sysAclMapper = ApplicationContextHelper.popBean(SysAclMapper.class);
SysAcl sysAcl = sysAclMapper.selectByPrimaryKey(1);
log.info(JsonUtils.objtoString(sysAcl)+"哈哈");
BeanValidator.check(vo);
return JsonData.success("test validator");
}