Spring中WebMvcConfigurer用到的JDK8特性

闲来无聊,随便翻看项目,发现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");
    }
}

测试输出

 

posted @ 2019-06-17 15:10  露娜妹  阅读(317)  评论(0编辑  收藏  举报