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中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

少年薄情凉人心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值