在Java Filter 中注入 Service方案一

新建一个类

package com.fulihui.yiyuanservice.common.util;

import javax.annotation.PostConstruct;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Component;

/**
 * Spring ApplicationContext工具,类通过 {@link Component}注解注入到bean容器,
 * 初始化时调用init方法,将ApplicationContext赋值到静态变量instance上。
 * @author Created by Willard.Hu on 2016/8/12 0012.
 */
@Component
public class ApplicationContextUtil extends ApplicationObjectSupport {
   

    private static ApplicationContext instance;

    public static ApplicationContext getContext() {
        return instance;
    }

    @PostConstruct
    private void init() {
        instance = getApplicationContext();
    }

}

web.xml配置

 <!--配置过滤器-->
       <filter>
          <filter-name>AuthenticationLoginFliter</filter-name>
          <filter-class>com.fulihui.yiyuanservice.web.filter.AuthenticationLoginFliter</filter-class>
          <init-param>  
             <param-name>forceEncoding</param-name>  
             <param-value>true</param-value>  
          </init-param>  
          <init-param>  
             <param-name>encoding</param-name>  
             <param-value>UTF-8</para
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值