原文地址:http://www.javayihao.top/detail/172

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帮助我们进行定制配置

Springboot关于tomcat容器配置、三大组件配置、拦截器配置的更多相关文章

  1. SpringBoot切换Tomcat容器,SpringBoot使用Jetty容器

    SpringBoot切换Tomcat容器, SpringBoot修改为Jetty容器, SpringBoot使用undertow容器, SpringBoot使用Jetty容器 ============ ...

  2. SpringBoot整合Mybatis完整详细版二:注册、登录、拦截器配置

    接着上个章节来,上章节搭建好框架,并且测试也在页面取到数据.接下来实现web端,实现前后端交互,在前台进行注册登录以及后端拦截器配置.实现简单的未登录拦截跳转到登录页面 上一节传送门:SpringBo ...

  3. Springboot 拦截器配置(登录拦截)

    Springboot 拦截器配置(登录拦截) 注意这里环境为springboot为2.1版本 1.编写拦截器实现类,实现接口   HandlerInterceptor, 重写里面需要的三个比较常用的方 ...

  4. springmvc以及springboot中的拦截器配置

    拦截器两种实现   如果不同的controller中都需要拦截器,不能使用相同的拦截器,因为拦截器不能跨controller,这个时候只能为不同的controller配置不同的拦截器,每一个拦截器只能 ...

  5. Struts2 拦截器配置以及实现

    @(Java ThirdParty)[Struts|Interceptor] Struts2 拦截器配置以及实现 Struts2的拦截器应用于Action,可以在执行Action的方法之前,之后或者两 ...

  6. Struts2学习笔记(拦截器配置添加)

    一.拦截器工作原理: 根据Struts2的工作原理图,拦截器在action执行前进行顺序调用,之后执行Action并返回结果字符串,再逆序调用拦截器.(结构类似递归方式...)大部分时候,拦截器方法都 ...

  7. Spring 拦截器配置

    Spring interceptor拦截器配置 Spring mvc的拦截器是通过handlerinterceptor来实现的 实现方式: 1.自定义一个类实现Spring的handlerinterc ...

  8. spring原拦截器配置与新命名空间mvc:interceptors配置拦截器对照与注意事项

    原先,我们是这么配置拦截器的 <bean id="openSessionInViewInterceptor"class="org.springframework.o ...

  9. Struts2拦截器配置

    1. 理解拦截器 1.1. 什么是拦截器: 拦截器,在AOP(Aspect-Oriented Programming)中用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作.拦截是AO ...

随机推荐

  1. Django对DateTimeField时间字段查询QuerySet为空的解决方案

    今天在用的Django中的filter()方法对DateTimeField字段查询时碰到了问题,抓耳挠腮一下午,终于解决了,我觉得花了一下午的时间怎么着也得记录下吧(无语)...... 问题描述 : ...

  2. Instrument API介绍

    1. Instrumentation介绍  JVMTI(JVM Tool Interface)是 Java 虚拟机所提供的 native 编程接口,是 JVMPI(Java Virtual Machi ...

  3. VS2019 开发Django(八)------视图

    导航:VS2019开发Django系列 这几天学习了一下Django的视图和模板,从这几天的学习进度来看,视图这里并没有花很多的时间,相反的,模板花费了大量的时间,主要原因还是因为对Jquery操作d ...

  4. Python 库打包分发、setup.py 编写、混合 C 扩展打包的简易指南(转载)

    转载自:http://blog.konghy.cn/2018/04/29/setup-dot-py/ Python 有非常丰富的第三方库可以使用,很多开发者会向 pypi 上提交自己的 Python ...

  5. python同步IO编程——StringIO、BytesIO和stream position

    主要介绍python两个内存读写IO:StringIO和BytesIO,使得读写文件具有一致的接口 StringIO 内存中读写str.需要导入StringIO >>> from i ...

  6. Android 避免内存泄漏

    什么是内存泄露? 就是该回收的内存由于种种原因没有被回收,还驻留在内存中. 内存泄露有什么影响? 可能一处小小的内存泄露就会导致整个应用卡顿,甚至崩溃. 例子说明: Toast.makeText(Ma ...

  7. Matplotlib的使用

    目录 1.pyplot基础语法 2.散点图与折线图 3.3D图与等高线图 1.pyplot基础语法 (1)创建画布 figure()创建一个空白画布,可以指定画布的大小figsize和设置分辨率dpi ...

  8. jquery-获取button的值

    <button id="test" name="test_name" value="test_value"></butto ...

  9. 大话设计模式Python实现-迭代器模式

    迭代器模式(Iterator Pattern):提供方法顺序访问一个聚合对象中各元素,而又不暴露该对象的内部表示. 下面是一个迭代器模式的demo: #!/usr/bin/env python # - ...

  10. Jmeter脚本参数化和正则匹配

    我们在做接口测试过程中,往往会遇到以下几种情况 每次发送请求,都需要更改参数值为未使用的参数值,比如手机号注册.动态时间等 上一个接口的请求体参数用于下一个接口的请求体参数 上一个接口的响应体参数用于 ...