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";
}
}