0 Basic Quick Start SpringBoot2.0 Tutorial (ii)

Source: Internet
Author: User

First, springboot2.x use Dev-tool hot deployment
Brief: Introduction to what is hot deployment, using Springboot combined with Dev-tool tool to quickly load launch apps

官方地址:https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#using-boot-devtools核心依赖包:    <dependency>           <groupId>org.springframework.boot</groupId>           <artifactId>spring-boot-devtools</artifactId>           <optional>true</optional>       </dependency>添加依赖后,在ide里面重启应用,后续修改后马上可以生效classloader不被热部署的文件    1、/META-INF/maven, /META-INF/resources, /resources, /static, /public, or /templates    2、指定文件不进行热部署 spring.devtools.restart.exclude=static/**,public/**    3、手工触发重启 spring.devtools.restart.trigger-file=trigger.txt        改代码不重启,通过一个文本去控制    https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#using-boot-devtools-restart-exclude注意点:生产环境不要开启这个功能,如果用java -jar启动,springBoot是不会进行热部署的

Second, springboot2.x configuration file explanation
Summary: springboot2.x Common configuration file XML, yml, properties differences and use

    xml、properties、json、yaml    1、常见的配置文件 xx.yml, xx.properties,        1)YAML(Yet Another Markup Language)            写 YAML 要比写 XML 快得多(无需关注标签或引号)            使用空格 Space 缩进表示分层,不同层次之间的缩进可以使用不同的空格数目            注意:key后面的冒号,后面一定要跟一个空格,树状结构        application.properties示例            server.port=8090              server.session-timeout=30              server.tomcat.max-threads=0              server.tomcat.uri-encoding=UTF-8         application.yml示例            server:                  port: 8090                  session-timeout: 30                  tomcat.max-threads: 0                  tomcat.uri-encoding: UTF-8     2、默认示例文件仅作为指导。 不要将整个内容复制并粘贴到您的应用程序中,只挑选您需要的属性。    3、参考:https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#common-application-properties    如果需要修改,直接复制对应的配置文件,加到application.properties里面

Iii. springboot annotation profiles automatically map to properties and entity classes combat
Description: Explain how to use @value annotation profiles to automatically map to attributes and entity classes

1, configuration file loading mode 11, controller above configuration @PropertySource ({"Classpath:resource.properties"}) 2, add properties    @Value ("${test.name}") private String name;  Mode two: Entity class configuration file steps: 1, add @Component annotations, 2, use @PropertySource annotations to specify the location of the configuration file, 3, use @ConfigurationProperties            Annotations, setting related properties, 4, must be injected into the IOC object resource in order to use the obtained profile value in the class.            @Autowired private serversettings serversettings; Example: @Configuration @ConfigurationProperties (prefix= "test") @PropertySource (VA  Lue= "Classpath:resource.properties") public class Serverconstant {FAQ: 1, configuration file injection failed, Could Not resolve placeholder resolved: According to the Springboot startup process, there will be an automatic scan package not scanned to the relevant annotations, the default spring framework implementation from the Declaration @componentsc The package of the class that is located is scanned for automatic injection, so the startup class is best placed under the root path, or you can specify the scan packet scope spring-boot scan startup class corresponding directories and subdirectories 2, injection               The Bean's way, the property name and the key one by one inside the configuration file correspond, add @value this annotation If not, add @value ("${xxx}") 

Iv. springboot personalized startup banner settings and debug logs
Summary: Customize app Launch fun log icons and view Debug logs

    1、启动获取更多信息 java -jar xxx.jar --debug    2、修改启动的banner信息        1)在类路径下增加一个banner.txt,里面是启动要输出的信息        2)在applicatoin.properties增加banner文件的路径地址             spring.banner.location=banner.txt        3)官网地址 https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-banners

V. springboot2.x Configuring Global Exception Combat
Explanation: Service-side exception explanation and Springboot configuration Global Exception Combat

    1、默认异常测试  int i = 1/0,不友好    2、异常注解介绍        @ControllerAdvice 如果是返回json数据 则用 RestControllerAdvice,就可以不加 @ResponseBody        //捕获全局异常,处理所有不可知的异常        @ExceptionHandler(value=Exception.class)

VI. springboot2.x Configuring global Exceptions Returns a custom page
Summary: Use Springboot to customize exceptions and Errors page Jump combat

1、返回自定义异常界面,需要引入thymeleaf依赖    <dependency>       <groupId>org.springframework.boot</groupId>       <artifactId>spring-boot-starter-thymeleaf</artifactId>    </dependency>2、resource目录下新建templates,并新建error.html    ModelAndView modelAndView = new ModelAndView();    modelAndView.setViewName("error.html");    modelAndView.addObject("msg", e.getMessage());    return modelAndView;    https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-error-handling

Seven, springboot start way to explain and deploy the war project to Tomcat9
Brief: Springboot Common startup ways to explain and deploy a war project Tomcat

1, IDE boot 2, jar package mode start maven plugin: <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-            maven-plugin</artifactid> </plugin> </plugins> </build> If not added, execute the JAR package with an error as follows Java-jar Spring-boot-demo-0.0.1-snapshot.jar no main manifest att                 Ribute, in Spring-boot-demo-0.0.1-snapshot.jar if there is a MVN Spring-boot:run project structure to install MAVEN Example.jar                 |  +-meta-inf | +-manifest.  MF +-org |     +-springframework |        +-boot |           +-loader |  +-<spring boot loader classes> +-boot-inf +-classes |     +-mycompany |     +-project               | +-yourclasses.class +-lib +-dependency1.jar +-DEPENDENCY2.J AR directory structure explained https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/# Executable-jar-jar-file-structure3, war package mode start 1) Modify packaged form jar to war <packaging>war</packaging> build project in Pom.xml Name <finalName>xdclass_springboot</finalName> 2) tocmat download https://tomcat.apache.org/download-90.cgi 3) Modify startup class public class Xdclassapplication extends Springbootservletinitializer {@Override Protec Ted Springapplicationbuilder Configure (Springapplicationbuilder application) {return application.sources (X            Dclassapplication.class); } public static void Main (string[] args) throws Exception {Springapplication.run (Xdclassapplica            Tion.class, args); }} 4) package The project, start the TOMCAT4, start the container introduction and the third-party test data explained using the Jmter Test tool to test performance, Qps,tps,rthttps://examples.javacodegeeks.com/enterprise-java/spring/ tomcat-vs-jetty-vs-undertow-comparison-of-spring-boot-embedded-servlet-containers/

Eight, in-depth springboot filter and Servlet3.0 configuration filter Combat
Introduction: Explain Springboot inside filter and use Servlet3.0 to configure custom filter combat

    filter简单理解:人--->检票员(filter)---> 景点    1、SpringBoot启动默认加载的Filter         characterEncodingFilter        hiddenHttpMethodFilter        httpPutFormContentFilter        requestContextFilter    2、Filter优先级        Ordered.HIGHEST_PRECEDENCE        Ordered.LOWEST_PRECEDENCE        低位值意味着更高的优先级 Higher values are interpreted as lower priority        自定义Filter,避免和默认的Filter优先级一样,不然会冲突        注册Filter的bean FilterRegistrationBean        同模块里面有相关默认Filter            web->servlet->filter    3、自定义Filter        1)使用Servlet3.0的注解进行配置        2)启动类里面增加 @ServletComponentScan,进行扫描        3)新建一个Filter类,implements Filter,并实现对应的接口        4) @WebFilter 标记一个类为filter,被spring进行扫描             urlPatterns:拦截规则,支持正则        6)控制chain.doFilter的方法的调用,来实现是否通过放行           不放行,web应用resp.sendRedirect("/index.html");            场景:权限控制、用户登录(非前端后端分离场景)等

1. Website address: https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/# Boot-features-embedded-container-servlets-filters-listeners

ix. annotations of Servlet3.0 native servlet combat
Explanation: Customizing native servlets and listener using Servlet3.0 annotations
1. Custom Native servlet

        @WebServlet(name = "userServlet",urlPatterns = "/test/customs")        public class UserServlet extends HttpServlet{             @Override             public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {                 resp.getWriter().print("custom sevlet");                 resp.getWriter().flush();                 resp.getWriter().close();             }             @Override             protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {                 this.doGet(req, resp);             }        }

Ten, Servlet3.0 's annotations native listener listener combat
Description: Listener Introduction and Servlet3.0 annotations customizing native listener listener Combat

    1、自定义Listener(常用的监听器 servletContextListener、httpSessionListener、servletRequestListener)        @WebListener        public class RequestListener implements ServletRequestListener {        @Override        public void requestDestroyed(ServletRequestEvent sre) {            // TODO Auto-generated method stub            System.out.println("======requestDestroyed========");        }        @Override        public void requestInitialized(ServletRequestEvent sre) {            System.out.println("======requestInitialized========");        }

Xi. springboot2.x Interceptor Combat and old and new configuration comparison
Introduction: Explain the Interceptor use, spingboot2.x new version Configuration Interceptor Interceptor and old version Springboot configuration Interceptor Difference Explanation

1、@Configuration    继承WebMvcConfigurationAdapter(SpringBoot2.X之前旧版本)    SpringBoot2.X 新版本配置拦截器 implements WebMvcConfigurer2、自定义拦截器 HandlerInterceptor    preHandle:调用Controller某个方法之前    postHandle:Controller之后调用,视图渲染之前,如果控制器Controller出现了异常,则不会执行此方法    afterCompletion:不管有没有异常,这个afterCompletion都会被调用,用于资源清理3、按照注册顺序进行拦截,先注册,先被拦截拦截器不生效常见问题:    1)是否有加@Configuration    2)拦截路径是否有问题 **  和 *     3)拦截器最后路径一定要 “/**”, 如果是目录的话则是 /*/Filter    是基于函数回调 doFilter(),而Interceptor则是基于AOP思想    Filter在只在Servlet前后起作用,而Interceptor够深入到方法前后、异常抛出前后等    依赖于Servlet容器即web应用中,而Interceptor不依赖于Servlet容器所以可以运行在多种环境。    在接口调用的生命周期里,Interceptor可以被多次调用,而Filter只能在容器初始化时调用一次。    Filter和Interceptor的执行顺序    过滤前->拦截前->action执行->拦截后->过滤后

The tutorial will continue to update ....

For more information, refer to: https://xdclass.net/html/course_catalogue.html?video_id=4

Http://edu.51cto.com/course/13539.html

0 Basic Quick Start SpringBoot2.0 Tutorial (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.