zoukankan      html  css  js  c++  java
  • 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");
    }
  • 相关阅读:
    HDU_1846 Brave Game(sg函数简化版)
    POJ 3225 Help with Intervals(线段树)
    ZOJ_3501 Roman Order
    HDU_1527 取石子游戏(威佐夫博弈)
    HDU_2112 HDU Today(DIjkstra + map映射)
    HDU_3339 In Action(Dijkstra + DP)
    单链表的实现(课本上的算法)
    haproxy 基于 uri 实现调度
    haproxy 基于 cookie 实现 session 绑定
    [转]ASP.NET 虚拟主机安全漏洞解决方案
  • 原文地址:https://www.cnblogs.com/yyzzkk/p/6708093.html
Copyright © 2011-2022 走看看