快速开发框架SpringBoot-学习日记(五)

本文深入探讨了SpringBoot的关键功能,包括单元测试的配置与执行,如何使用拦截器、Servlet和Filter进行请求处理,以及基于war包的项目构建和非web项目的创建方法。通过实例演示了如何在SpringBoot中集成测试依赖,定义和使用自定义的Servlet、Filter和拦截器,为读者提供了全面的SpringBoot实践指导。

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

第2章 Spring Boot重要用法

单元测试

要保证两点:

  1. pom中要有测试的依赖(只要你不专门删除,SpringBoot中就存在该依赖)
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
  1. 测试类在src/test/java目录中已经创建好了,需要在测试类类头上要添加两个注解
@RunWith(SpringRunner.class)
// classes用于指定被测内容的启动类
@SpringBootTest(classes = Application09Test.class)
public class Application09TestTests {

    @Autowired
    private SomeService service;
    @Test
    public void doSome() {
        System.out.println(service.doSome());
    }
}

Spring Boot中使用拦截器

定义拦截器

public class SomeIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("执行拦截器");
        return true;
    }
}

定义拦截器注册类

@Configuration  // 表示当前类充当着Spring配置文件
public class MyConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SomeIntercepter())
                // .addPathPatterns("/**/some");   // 表示拦截所有以/some结尾的请求
                // .addPathPatterns("/test/**");   // 表示拦截所有以/test开头的请求
                    // 除了/other结尾的请求外,拦截所有请求
                   .addPathPatterns("/**").excludePathPatterns("/**/other");
    }
}

Spring Boot中使用Servlet

配置类方式

适用于Servlet2.5及Servlet3.0及以上版本

  1. 定义Servlet
public class SomeServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().println("spring boot servlet");
    }
}
  1. 定义配置类
@Configuration
public class ConsumerApplicationContext {

    @Bean
    public ServletRegistrationBean<SomeServlet> getServletBean() {
        SomeServlet someServlet = new SomeServlet();
        return new ServletRegistrationBean<SomeServlet>(someServlet, "/some");
    }
}

注解方式

仅适用于Servlet3.0及其以上版本

  1. 定义Servlet。该Servlet上需要使用@WebServlet注解
@WebServlet("/some")
public class SomeServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().println("spring boot servlet");
    }
}
  1. 在启动类上添加如下注解
// 需要指定要扫描的Servlet所在的包路径
@ServletComponentScan("com.bjpowernode.servlet")
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Spring Boot中使用Filter

配置类方式

适用于Servlet2.5及Servlet3.0及以上版本

  1. 定义Filter
public class SomeFilter implements Filter {
    public void destroy() {
    }

    public void init(FilterConfig config) throws ServletException {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("执行过滤器");
        chain.doFilter(req, resp);
    }
}
  1. 定义配置类
    在配置类中添加如下方法
    @Bean
    public FilterRegistrationBean<SomeFilter> getFilterBean() {
        SomeFilter someFilter = new SomeFilter();
        FilterRegistrationBean<SomeFilter> registrationBean = new FilterRegistrationBean<>(someFilter);
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }

注解方式

仅适用于Servlet3.0及其以上版本

  1. 定义Filter。该Filter上需要使用@WebFilter注解
@WebFilter("/*")
public class SomeFilter implements Filter {
    public void destroy() {
    }

    public void init(FilterConfig config) throws ServletException {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("执行过滤器");
        chain.doFilter(req, resp);
    }
}
  1. 在启动类上添加如下注解
// 需要指定要扫描的Servlet及Filter所在的包路径
@ServletComponentScan("com.bjpowernode.*")
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

基于war的spring boot工程

创建工程时选择war,而非jar即可。

创建非web工程

  1. 在创建工程时不要导入web依赖
  2. 在启动类中可以获取到Spring容器对象
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        // 获取Spring容器对象
        ConfigurableApplicationContext ac = SpringApplication.run(Application.class, args);
        SomeService service = (SomeService) ac.getBean("someServiceImpl");
        System.out.println(service.doSome());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值