Spring中WebMvcConfigurer用到的JDK8特性

博主翻看项目发现Java的WebMvcConfigurerAdapter已过时,推荐实现类直接继承WebMvcConfigurer。但实现接口需实现所有方法,而WebMvcConfigurer能适配,原因是JDK8通过default或static关键字改变了接口不能有方法体的规则,还创建实现类进行测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

闲来无聊,随便翻看项目,发现WebMvcConfigurerAdapter已经过时了,它的作用也不用说了,就是起到适配器的作用,让实现类不用实现所有方法,可以根据实际需要去实现需要的方法。

@Deprecated
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {

    /**
     * {@inheritDoc}
     * <p>This implementation is empty.
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
    }
    
    ...
}

这个废弃了,那么推荐的方式呢?是实现类直接去继承 WebMvcConfigurer 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyWebConfig implements WebMvcConfigurer {

    @Autowired
    private CommonInterceptor commonInterceptor;

    /**
     * 配置拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(commonInterceptor).addPathPatterns("/**").excludePathPatterns("/login");
    }
}

那么问题来了,我们都知道,实现接口是要实现其中的所有方法的,它是怎样做到 适配 的呢?我们打开 WebMvcConfigurer 看一下

public interface WebMvcConfigurer {

    /**
     * Helps with configuring HandlerMappings path matching options such as trailing slash match,
     * suffix registration, path matcher and path helper.
     * Configured path matcher and path helper instances are shared for:
     * <ul>
     * <li>RequestMappings</li>
     * <li>ViewControllerMappings</li>
     * <li>ResourcesMappings</li>
     * </ul>
     * @since 4.0.3
     */
    default void configurePathMatch(PathMatchConfigurer configurer) {
    }
... }

我们都知道,刚开始接触Java的时候,定义接口是不允许有方法体的!可是,JDK8改变了这个规则,通过default或者static关键字。比如这样

public interface MyInterface {

    default void add(int a, int b) {
        System.out.println(a + b);
    }

    default void doSomething() {
    }

    static void hello(String name) {
        System.out.println("Hello! " + name);
    }
}

接下来创建一个实现类(只实现了部分方法)

public class MyInterfaceImpl implements MyInterface {

    public static void main(String[] args){
        MyInterface.hello("Tom");
        new MyInterfaceImpl().add(1,2);
        new MyInterfaceImpl().doSomething();
    }

    @Override
    public void doSomething() {
        System.out.println("Do Something");
    }
}

测试输出

 

转载于:https://www.cnblogs.com/LUA123/p/11039794.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值