Springboot中tomcat配置、三大组件配置、拦截器配置

简介: Springboot中tomcat配置、三大组件配置、拦截器配置

1.tomcat配置

Springboot默认使用的就是嵌入式servlet容器即tomcat,对于web项目,如果使用的是外部tomcat,相关配置比如访问端口、资源路径等可以在tomcat的conf文件下配置。但是在boot中,tomcat配置又两种方式

第一种:通过配置文件直接配置(推荐)

#如果是tomcat相关的设置用server.tomcat.xx
server.tomcat.uri-encoding=UTF-8
#如果是servlet相关的配置用server.xx
server.port=80

第二种:通过配置类的方式


3.Springboot中定义拦截器组件

先定义一个拦截器组件

package com.javayihao.top.blog.interceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断session中是否存在用户
        if (request.getSession().getAttribute("user") == null) {
            response.sendRedirect("/admin");
            return false;
        }
        return true;
    }
 
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
 
    }
 
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
 
    }
}

然后将这个组件加入到boot中,在boot1版本中 通过继承WebmvcConfigureAdapter实现一个web配置,例如我们配置上面的拦截器

@Configuration //声明这是一个配置
public class LoginInterceptorConfig extends WebMvcConfigurerAdapter {
@Resource
private LoginInterceptor loginInterceptor;
 
@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(loginInterceptor).addPathPatterns("/admin/**").excludePathPatterns("/admin").excludePathPatterns("/admin/login");
}
    }

 

或者直接使用匿名类的方式

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * 自定义一个登陆拦截器
 */
@Configuration //声明这是一个配置
public class LoginInterceptor extends WebMvcConfigurerAdapter {
    /*
    用来添加拦截器的方法
    InterceptorRegistry registry拦截器注册
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //使用匿名内部类创建要给拦截器
        HandlerInterceptor loginInterceptor = new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
                //判断session中是否存在用户
                if (request.getSession().getAttribute("user") == null) {
                    response.sendRedirect("/admin");
                    return false;
                }
                return true;
            }
 
            @Override
            public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
 
            }
 
            @Override
            public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
 
            }
        };
        registry.addInterceptor(loginInterceptor).addPathPatterns("/admin/**").excludePathPatterns("/admin").excludePathPatterns("/admin/login");
    }
}

 

对于Sprinboot2版本,第一步还是定义一个拦截器组件

第二不再是通过继承WebmvcConfigureAdapter实现一个web配置,而是实现接口WebMvcConfigurer增加一个配置

@Configuration
public class WebConfig implements WebMvcConfigurer {
 
//引入我们的拦截器组件
    @Resource
    private LoginInterceptor loginInterceptor;
//实现拦截器配置方法
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor).addPathPatterns("/admin/**").excludePathPatterns("/admin").excludePathPatterns("/admin/login");
 
    }
}

4.Springboot中定义组件的方式

第一种是通过xml的配置方式;第二种是通过全注解的方式

建立一个测试类

public class TestService {
}

新建一个beans.xml,写一个service的bean配置

 

<?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="testService"></bean>
</beans>

然后可以Application类里直接引用,也可以加载Configuration配置类上面

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
//Springboot中没有Spring配置文件,我们要想使自己写的文件配置进去,就通过ImportResource让配置文件里面的内容生效
@SpringBootApplication
@ImportResource(locations = {"classpath:beans.xml"})
public class SpringbootPropertiesConfigApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(SpringbootPropertiesConfigApplication.class, args);
    }
 
}
@SpringBootTest
class SpringbootPropertiesConfigApplicationTests {
 
    //装载ioc容器
    @Autowired
    ApplicationContext ioc;
 
    @Test
    void contextLoads() {
        //测试这个bean是否已经加载到Spring容器
        boolean flag =  ioc.containsBean("testService");
        System.out.println(flag);
    }
 
}

 

经过测试,返回的是true,ok,换Springboot注解的方式实现

新建一个PropertiesConfig配置类,注意:组件的id就是方法名

import com.example.springboot.properties.service.TestService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration //@Configuration注解实践上也是一个Component
public class PerpertiesConfig {
    //通过@Bean注解将组件添加到Spring容器,组件的id就是方法名
    @Bean
    public TestService testService1(){
        return new TestService();
    }
}

测试

@SpringBootTest
class SpringbootPropertiesConfigApplicationTests {
 
    @Autowired
    ApplicationContext ioc;
 
    @Test
    void contextLoads() {
        //传方法名testService1
        boolean flag =  ioc.containsBean("testService1");
        System.out.println(flag);
    }
 
}

 

Junit测试,返回的还是TRUE,如果改下name为testService就是返回FALSE的,因为组件名称就是@Bean注解对应的方法名

其实以前写Spring项目的时候,很显然也可以用@Service或者@Controller注解将组件添加到容器里,如果你去点一下源码,其实这些注解都有一个共同点就是都引入了@Component注解,而@Configuration注解,本质上也是引入了@Component注解,而@Bean是没有引入的,所以,如果你只加@Bean,而不加@Configuration注解的情况,是不可以将组件添加到Spring容器的

 

总结:关于Springboot自动配置组件的时候注意的三点

1.先看容器中有没有自己需要的组件,如果又,直接使用即可。如果没有自己需要的组件,自己配置

2.Springboot中有许多的xxxConfiguer帮助我们进行扩展配置

3.Springboot中有许多的xxxCustomizer帮助我们进行定制配置



相关文章
|
3月前
|
监控 Java 应用服务中间件
Spring Boot整合Tomcat底层源码分析
【11月更文挑战第20天】Spring Boot是一个用于快速构建基于Spring框架的应用程序的开源框架。它通过自动配置和起步依赖等特性,大大简化了Spring应用的开发和部署过程。本文将深入探讨Spring Boot的背景历史、业务场景、功能点以及底层原理,并通过Java代码手写模拟Spring Boot的启动过程,特别是其与Tomcat的整合。
89 1
|
3天前
|
Cloud Native Java Nacos
springcloud/springboot集成NACOS 做注册和配置中心以及nacos源码分析
通过本文,我们详细介绍了如何在 Spring Cloud 和 Spring Boot 中集成 Nacos 进行服务注册和配置管理,并对 Nacos 的源码进行了初步分析。Nacos 作为一个强大的服务注册和配置管理平台,为微服务架构提供
29 14
|
6天前
|
Java 数据库 开发者
详细介绍SpringBoot启动流程及配置类解析原理
通过对 Spring Boot 启动流程及配置类解析原理的深入分析,我们可以看到 Spring Boot 在启动时的灵活性和可扩展性。理解这些机制不仅有助于开发者更好地使用 Spring Boot 进行应用开发,还能够在面对问题时,迅速定位和解决问题。希望本文能为您在 Spring Boot 开发过程中提供有效的指导和帮助。
43 12
|
3月前
|
Java 开发者 微服务
手写模拟Spring Boot自动配置功能
【11月更文挑战第19天】随着微服务架构的兴起,Spring Boot作为一种快速开发框架,因其简化了Spring应用的初始搭建和开发过程,受到了广大开发者的青睐。自动配置作为Spring Boot的核心特性之一,大大减少了手动配置的工作量,提高了开发效率。
83 0
|
26天前
|
监控 前端开发 Java
SpringBoot集成Tomcat、DispatcherServlet
通过这些配置,您可以充分利用 Spring Boot 内置的功能,快速构建和优化您的 Web 应用。
57 21
|
1月前
|
JavaScript Java 程序员
SpringBoot自动配置及自定义Starter
Java程序员依赖Spring框架简化开发,但复杂的配置文件增加了负担。SpringBoot以“约定大于配置”理念简化了这一过程,通过引入各种Starter并加载默认配置,几乎做到开箱即用。
127 10
SpringBoot自动配置及自定义Starter
|
1月前
|
网络协议 Java 应用服务中间件
centos7环境下tomcat8的安装与配置
本文介绍了在Linux环境下安装和配置Tomcat 8的详细步骤。首先,通过无网络条件下的文件交互软件(如Xftp 6或MobaXterm)下载并解压Tomcat安装包至指定路径,启动Tomcat服务并测试访问。接着,修改Tomcat端口号以避免冲突,并部署Java Web应用项目至Tomcat服务器。最后,调整Linux防火墙规则,确保外部可以正常访问部署的应用。关键步骤包括关闭或配置防火墙、添加必要的端口规则,确保Tomcat服务稳定运行。
|
2月前
|
Java Maven Spring
SpringBoot配置跨模块扫描问题解决方案
在分布式项目中,使用Maven进行多模块开发时,某些模块(如xxx-common)没有启动类。如何将这些模块中的类注册为Spring管理的Bean对象?本文通过案例分析,介绍了两种解决方案:常规方案是通过`@SpringBootApplication(scanBasePackages)`指定扫描路径;推荐方案是保持各模块包结构一致(如com.xxx),利用SpringBoot默认扫描规则自动识别其他模块中的组件,简化配置。
SpringBoot配置跨模块扫描问题解决方案
|
2月前
|
NoSQL Java Redis
Spring Boot 自动配置机制:从原理到自定义
Spring Boot 的自动配置机制通过 `spring.factories` 文件和 `@EnableAutoConfiguration` 注解,根据类路径中的依赖和条件注解自动配置所需的 Bean,大大简化了开发过程。本文深入探讨了自动配置的原理、条件化配置、自定义自动配置以及实际应用案例,帮助开发者更好地理解和利用这一强大特性。
188 14
|
3月前
|
缓存 IDE Java
SpringBoot入门(7)- 配置热部署devtools工具
SpringBoot入门(7)- 配置热部署devtools工具
194 1
SpringBoot入门(7)- 配置热部署devtools工具