Java在ServletContextListener、过滤器、拦截器解决对象无法注入问题
2024-09-23 19:29:08
1、通用方法:
// 数据库日志操作对象
private LogInfoServiceIFC logInfoServiceProxy;
@Override
public void contextInitialized(ServletContextEvent event) {
WebApplicationContext context = WebApplicationContextUtils
.getRequiredWebApplicationContext(event.getServletContext());
logInfoServiceProxy = (LogInfoServiceIFC) context.getBean("logInfoService");
}
2、SpringMVC项目可直接在类方法中加入下面这句话:
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
3.从网上看到的,类似1,过滤器中注入对象,可行
工具类:
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component; @Slf4j
@Component
public class SpringUtils implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
if (SpringUtils.applicationContext == null) {
SpringUtils.applicationContext = applicationContext;
} } public static ApplicationContext getApplicationContext() {
return applicationContext;
} //根据name
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
} //根据类型
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
} public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
} }
使用:
if (userService == null) {
userService = (UserService) SpringUtils.getBean("userServiceImpl");
}
最新文章
- Unity3D Animation Curve
- Newtonsoft.Json 的解析用法。
- 解决chi_sim.traineddata报read_params_file: parameter not found: allow_blob_division
- netbeans php安装、调试
- Android实现推送方式解决方案(转)
- awt可视化界面上传数据到mysql,jsp通过jdbc方式查询数据库,并将结果打印在网页上
- HDU 4118 Holiday&#39;s Accommodation
- 对React的理解
- java后台开发- NOTE
- 关于扩展IP地址空间的几个方案的探讨
- BZOJ2744: [HEOI2012]朋友圈
- Beyond Compare 3.3.8 build 16340 + Key
- python面试宝典2018最新版
- 第k个素因子只有3 5 7 的数
- How do I improve my English speaking skills in a very short time?
- 从零开始学习html(八)CSS选择器——上
- 变量与算术表达式 - C程序设计语言
- Java String和StringBuffer和StringBuilder
- Python.Books
- App云测试服务对比