springboot(15)- 整合web开发(7)- 加载 xml 配置,注册拦截器

1 加载 xml 配置文件

package com.tzb;

public class SayHello {

    public String sayHello(){
        return "hello xml";
    }
}

  • beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="sayHello" class="com.tzb.SayHello"></bean>
</beans>
  • 配置类
package com.tzb;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource(locations = "classpath:beans.xml")
public class WebMvcConfig {

}


  • 单元测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class XmlApplicationTests {

    @Autowired
    private SayHello sayHello;

    @Test
    public void contextLoads() {
        System.out.println(sayHello.sayHello());
    }

}

在这里插入图片描述

2 注册拦截器

  • 拦截器类
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("preHandle");

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}

  • 配置类
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    MyInterceptor myInterceptor(){
        return new MyInterceptor();
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor()).addPathPatterns("/**");
    }
}

  • Controller
@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

}

在这里插入图片描述
在这里插入图片描述

相关推荐
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页