ssm的filter中注入bean失败

项目是采用了ssm+spring security(spring security整合在controller层)
我是在service层实现的日志功能,需要获取到username(操作者名字)
在controller层可以获取到当前操作者的名字,通过这样可以获取到

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetails principal = (UserDetails) authentication.getPrincipal();
 String username = principal.getUsername()

在service层中获取Authentication为null
后来想着在controller中用过滤器把username加入redis中,发现JedisPool也注入不了。是因为listen,filter,servlet的执行顺序是listen>filter>servlet,进行servlet的时候,servlet还没把bean注入spring容器中,所以获取不到。
通过在网上找到的一个方法

package com.it.application;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component("applicationContextHelper")
public class ApplicationContextHelper implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    public static <T> T getBean(Class<T> clazz) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(clazz);
    }
}

再在springMVC的配置文件中将其注入spring容器

<bean class="com.itwangpt.application.ApplicationContextHelper" lazy-init="false" />`

然后在filter中

public class GetUsernameFilter implements Filter {


    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        JedisPool jedisPool = ApplicationContextHelper.getBean(JedisPool.class);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            UserDetails principal = (UserDetails) authentication.getPrincipal();
            String username = principal.getUsername();
            jedisPool.getResource().set("FORHealthLogUserName", username);
            chain.doFilter(request, response);
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}

成功获取到了jedisPool对象,并将username加入了redis中

发布了3 篇原创文章 · 获赞 0 · 访问量 128

猜你喜欢

转载自blog.csdn.net/weixin_44990342/article/details/104296046
今日推荐