在Filter中注入Service

贴一段代码简单明了:

@WebFilter(filterName = "MainFilter",urlPatterns = "/*")
public class MainFilter implements Filter {

    private UserService userService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ApplicationContext ctx = WebApplicationContextUtils
                .getRequiredWebApplicationContext(filterConfig.getServletContext());
        userService = ctx.getBean(UserService.class);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
           filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

就这样,userService就可以正常使用了

我的个人博客地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过以下步骤实现在Springboot启动后通过service的方法修改filter内的属性: 1. 在你的filter添加需要修改的属性,并提供getter和setter方法。 2. 在你的service注入filter,并通过setter方法修改filter内的属性。 3. 在Springboot启动后,使用ApplicationContext获取你的service,并调用需要修改filter属性的方法。 以下是一个简单的示例: ```java // Filter public class MyFilter implements Filter { private boolean enabled = true; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (enabled) { // do something } chain.doFilter(request, response); } } // Service @Service public class MyService { @Autowired private MyFilter myFilter; public void enableFilter() { myFilter.setEnabled(true); } public void disableFilter() { myFilter.setEnabled(false); } } // 在Springboot启动后调用service的方法 public static void main(String[] args) { SpringApplication.run(Application.class, args); ApplicationContext context = new AnnotationConfigApplicationContext(Application.class); MyService myService = context.getBean(MyService.class); // 启用filter myService.enableFilter(); // 禁用filter myService.disableFilter(); } ``` 在上面的示例,我们注入了一个MyFilter的实例,并通过MyService的方法启用或禁用该filter。在Springboot启动后,我们可以通过ApplicationContext获取MyService,并调用需要修改filter属性的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值