Java在ServletContextListener、过滤器、拦截器解决对象无法注入问题

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");
}
原文地址:https://www.cnblogs.com/yyzzkk/p/6708093.html