Spring Boot Micro Framework
- Introduction to spring boot
Spring Boot is a new framework provided by the Pivotal team, designed to simplify the initial build and development process of Spring applications. The framework uses a specific way to configure, so that developers no longer need to define templated configurations. In this way, Spring Boot is committed to becoming a leader in the booming rapid application development field.
Spring boot (micro framework) = spring MVC (controller) + spring (project management)
- Characteristics of spring boot
Create a stand-alone Spring application
Embedded Tomcat, without deploying WAR files
Simplified Maven configuration
Automatically configure Spring
No XML configuration
- springboot environment building
Environmental requirements:
MAVEN 3.x+
Spring FrameWork 4.x+
JDK7.x +
Spring Boot 1.5.x+
3.1 Introducing dependencies into projects
<!--inherit springboot The parent project--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.7.RELEASE</version> </parent> <dependencies> <!--Introduce springboot Of web Support--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
3.2 Introducing Configuration Files
src/main/resources/application.yml in the project
3.3 Packaging and Controller Creation
// Create the specified package structure in the project
com +| baizhi +| controller */ @Controller @RequestMapping("/hello") public class HelloController { @RequestMapping("/hello") @ResponseBody public String hello(){ System.out.println("======hello world======="); return "hello"; } }
3.4 Writing Entry Classes
// Create the entry class Application in the following package structure in the project
/* com +| baizhi */ @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }
3.5 Run main startup project
o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8989 (http) com.baizhi.Application : Started Application in 2.152 seconds (JVM running for 2.611)
// Note: The above logs indicate that the startup was successful
3.6 Access Projects
// Note: springboot projects do not have project names by default
// Access path: http://localhost:8080/hello/hello
4. Starting tomcat Port Occupancy Problem
server:
port: 898989 # to specify the embedded server port number
context-path: /springboot # to specify the access path for the project
5. springboot annotations
/* Description: Sprboot usually has a class named xxxApplication, and the entry class has a main method, in which SpringApplication.run(xxxApplication.class,args) is used to start the spring boot application project. @ RestController: The @Controller+@ResponseBody combination supports RESTful access and returns json strings. @ The SpringBoot Application annotation is equivalent to: @ Configuration project start-up automatically configures spring and spring MVC initial build @ Enable AutoConfiguration automatically integrates with third-party technologies integrated in the project @ ComponentScan scans the annotations in subpackages and subpackages of entry classes */
-
Splitting Configuration Files in springboot
# Explanation: In the actual development process, the production environment and the test environment may be different, so it is necessary to separate the configuration in production from that in testing. In spring boot, it also provides the way to split the configuration file. Here, take the inconsistent name of production item as an example:Projects in production are named: cmfz
The project name in the test is: spring boot
Port at the same time: 8080
The breakdown is as follows:
# Main Profile:
application.yml # is used to write the same configuration
server:
port: 8080 # Production and testing for the same port
#Production Profile: application-pord.yml server: context-path: /cmfz #Test configuration file: application-dev.yml server: context-path: /springboot
- Integrated jsp presentation in spring boot
7.1 Integrated jar package with jsp
<dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency>
7.2 Introducing jsp Running Plug-in
<build> <finalName>springboot_day1</finalName> <!--Introduce jsp Running plug-ins--> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
7.3 Configuration View Parser
# Introducing View Parser in Configuration File
spring:
mvc:
view:
prefix: / #/ Represents access to webapp pages in the project
suffix: .jsp
7.4 Start accessing jsp pages
http://localhost:8989/cmfz/index.jsp
8. springboot integration mybatis
8.1 Introducing Dependency
<!--integration mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.3</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.12</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency>
Note: Because springboot integrates mybatis version by default and relies on mybatis, no additional mybati version is required, otherwise conflicts will occur.
8.2 Configuration Profile
spring: mvc: view: prefix: / suffix: .jsp datasource: type: org.apache.commons.dbcp.BasicDataSource #Specify connection pool type driver-class-name: com.mysql.jdbc.Driver #Designated Driver url: jdbc:mysql://localhost:3306/cmfz # Specified url username: root #Specify user name password: root #Specify a password
8.3 Add mybatis configuration
# Add the following configuration to the configuration file:
mybatis:
mapper-locations: classpath:com/baizhi/mapper/*.xml# Specifies the location of mapper configuration file
type-aliases-package: com.baizhi.entity# Class with aliases specified
// Add the following configuration to the entry class:
@SpringBootApplication
@ MapperScan("com.baizhi.dao")// / This configuration must be added to the entry class
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
8.4 tabulation
CREATE TABLE `t_clazz` ( `id` varchar(40) NOT NULL, `name` varchar(80) DEFAULT NULL, `no` varchar(90) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8.5 Developing Entity Classes
public class Clazz { private String id; private String name; private String no; //The get set method omits... }
8.6 Developing DAO Interface and Mapper
public interface ClazzDAO { List<Clazz> findAll(); } <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.baizhi.dao.ClazzDAO"> <select id="findAll" resultType="Clazz"> select * from t_clazz </select> </mapper>
8.7 Development Service and Implementation
//Interface public interface ClazzService { List<Clazz> findAll(); } //Realization @Service @Transactional public class ClazzServiceImpl implements ClazzService { @Autowired private ClazzDAO clazzDAO; @Transactional(propagation = Propagation.SUPPORTS) @Override public List<Clazz> findAll() { return clazzDAO.findAll(); } }
8.8 Introducing Test Dependence
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
8.9 Writing Test Classes
@RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) public class TestClazzService { @Autowired private ClazzService clazzService; @Test public void test(){ List<Clazz> all = clazzService.findAll(); for (Clazz clazz : all) { System.out.println(clazz); } } }
9. Open hot deployment of jsp pages
9.1 Introduction
In spring boot, jsp runs as production mode by default, and changes are not allowed to take effect immediately after content is saved. Therefore, in the development process, we need to debug jsp pages every time we need to restart the server, which greatly affects our efficiency. For this reason, spring boot provides that we can modify the default production mode to debug mode and change it to debug mode. After the mode is saved, it will take effect immediately. How to configure the test mode needs to add the following configuration in the configuration file to modify it to the development mode.
9.2 Configuration Open Test Mode
server: port: 8989 jsp-servlet: init-parameters: development: true #Debugging mode for opening jsp pages
10. hot deployment of devtools in spring boot
10.1 Introduction
In order to further improve the efficiency of development, spring boot provides us with global project hot deployment. After modifying some codes and related configuration files in the development process, we do not need to restart every time to make the modification effective. After the spring boot global hot deployment is turned on in the project, we only need to wait a few seconds to make the modification after the modification. Take effect.
10.2 Open Hot Deployment
Introduction of dependencies in 10.2.1 projects
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency>
10.2.2 Setting idea to Support Automatic Compilation
1. Turn on automatic compilation
Preferences | Build, Execution, Deployment | Compiler - > Check the Build project automation option
2. Open to allow file modification during runtime
CTRL + Alt + shift +/ --> Select 1.Registry - > Check compiler.automake.allow.when.app.running
10.2.3 Start-up project to check whether hot deployment is effective
1. The following logs appear when the startup takes effect
2019-07-17 21:23:17.566 INFO 4496 --- [ restartedMain] com.baizhi.InitApplication : Starting InitApplication on chenyannandeMacBook-Pro.local with PID 4496 (/Users/chenyannan/IdeaProjects/ideacode/springboot_day1/target/classes started by chenyannan in /Users/chenyannan/IdeaProjects/ideacode/springboot_day1) 2019-07-17 21:23:17.567 INFO 4496 --- [ restartedMain] com.baizhi.InitApplication : The following profiles are active: dev 2019-07-17 21:23:17.612 INFO 4496 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@66d799c5: startup date [Wed Jul 17 21:23:17 CST 2019]; root of context hierarchy 2019-07-17 21:23:18.782 INFO 4496 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8989 (http) 2019-07-17 21:23:18.796 INFO 4496 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2019-07-17 21:23:18.797 INFO 4496 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.20
Note: restartedMain logs indicate that it is in effect. If you encounter modifications when using hot deployment and cannot take effect, please try restarting the project for trial.
- logback Log Integration
11.1 logback Brief Introduction
Logback is another open source log component designed by the founder of log4j. At present, logback is divided into three modules: logback-core, logback-classic and logback-access. Further improvements to log4j log display
11.2 Log Level
DEBUG < INFO < WARN < ERROR Log level from low to high: the higher the log level, the less log information output
Log Classification in 11.3 Project
Logs fall into two categories
One is rootLogger: used to monitor all running logs in a project, including the introduction of logs in dependent jar s
One is logger: used to listen for log information in specified packages in projects
11.4 Use in Java projects
11.4.1 logback configuration file
The logback configuration file must be placed in the project root directory and the name must be logback.xml <?xml version="1.0" encoding="UTF-8" ?> <configuration> <! - Define the log output location in the project - > <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender"> <! - Defines the log output format for the project - > <! - Defines the log output format for the project - > <layout class="ch.qos.logback.classic.PatternLayout"> <pattern> [%p] %d{yyyy-MM-dd HH:mm:ss} %m %n</pattern> </layout> </appender> <! - Log Control in Project <root level="INFO"> <appender-ref ref="stdout"/> </root> <! - Specified package log control in the project - > <logger name="com.baizhi.dao" level="DEBUG"/>
@Controller @RequestMapping("/hello") public class HelloController { //Declare log members private static Logger logger = Logger.getLogger(HelloController.class); @RequestMapping("/hello") @ResponseBody public String hello(){ System.out.println("======hello world======="); logger.debug("DEBUG"); logger.info("INFO"); logger.warn("WARN"); logger.error("ERROR"); return "hello"; } }
- Section programming
12.1 Introduction
springboot is a further encapsulation of spring framework and spring MVC in the original project, so AOP programming in spring framework is also supported in spring boot, but only annotated programming is provided in spring boot for rapid development.
12.2 Use
12.2.1 Introducing Dependency
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
12.2.2 Relevant Notes
/** @ Aspect is used on a class, representing that class as a facet @ Before is used to represent this method in a way that is a pre-notification method. @ After represents this method in method is a post-notification method @Around represents this method in method is a surround method. @ Around is used to represent the method as a surround method. **/
12.2.3 Front Section
@Aspect @Component public class MyAspect { @Before("execution(* com.baizhi.service.*.*(..))") public void before(JoinPoint joinPoint){ System.out.println("Before advice"); joinPoint.getTarget();//Target object joinPoint.getSignature();//Method signature joinPoint.getArgs();//Method parameters } }
12.2.4 Posterior Section
@Aspect @Component public class MyAspect { @After("execution(* com.baizhi.service.*.*(..))") public void before(JoinPoint joinPoint){ System.out.println("after returning advise"); joinPoint.getTarget();//Target object joinPoint.getSignature();//Method signature joinPoint.getArgs();//Method parameters } }
Note: Neither the pre-notification nor the post-notification returns a value. The method parameters are joinpoint.
12.2.5 circumferential section
@Aspect @Component public class MyAspect { @Around("execution(* com.baizhi.service.*.*(..))") public Object before(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { System.out.println("Entry surround notification"); proceedingJoinPoint.getTarget();//Target object proceedingJoinPoint.getSignature();//Method signature proceedingJoinPoint.getArgs();//Method parameters Object proceed = proceedingJoinPoint.proceed();//Release the target execution method System.out.println("Return to surround notification after execution of the target method"); return proceed;//Return the return value of the target method } }
Note: There is a return value around the notification. The parameter is ProceedingJoinPoint. If the release is performed, the target method will not be executed. Once released, the return value of the target method must be returned. Otherwise, the caller cannot accept the return data**
- File upload and download
13.1 File Upload
13.1.1 Prepare to upload pages
<form action="Route...." method="post" enctype="multipart/form-data"> <input type="file" name="aa"> <input type="submit" value="upload"> </form>
- Form submission must be post
- The enctype attribute of the form must be multipart/form-data
- The background acceptance variable name should be consistent with the file selection name attribute
13.1.2 Writing Controller
@Controller @RequestMapping("/file") public class FileController { @RequestMapping("/upload") public String upload(MultipartFile aa, HttpServletRequest request) throws IOException { String realPath = request.getRealPath("/upload"); aa.transferTo(new File(realPath,aa.getOriginalFilename()));//File upload return "index"; } }
13.1.3 Modify file upload size
# The following exception occurred when uploading: the size of the uploaded file exceeds the default configuration of 10M.
nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (38443713) exceeds the configured maximum (10485760)
# Modify the upload file size:
spring: http: multipart: max-request-size: 209715200 #Limitation used to control file upload size max-file-size: 209715200 #Used to specify the maximum file size on the server side
13.2 File Download
13.2.1 Provides links to downloaded files
<a href="../file/download?fileName=corejava.txt">corejava.txt</a>
13.2.2 Development of Controller
@RequestMapping("/download") public void download(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception { String realPath = request.getRealPath("/upload"); FileInputStream is = new FileInputStream(new File(realPath, fileName)); ServletOutputStream os = response.getOutputStream(); response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8")); IOUtils.copy(is,os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); }
- Interceptor
14.1 Development of Interceptors
public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception { System.out.println("======1====="); return true;//Return true, release, return false block } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception { System.out.println("=====2====="); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception { System.out.println("=====3====="); } }
14.2 Configuration of Interceptor
@Component public class InterceptorConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { //Adding interceptors registry.addInterceptor(new MyInterceptor()) .addPathPatterns("/**")//Define Interception Path .excludePathPatterns("/hello/**"); //Excluding Interception Path } }
- war package deployment
15.1 Set the packaging mode to war
war
15.2 Specify the entry class in the plug-in
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <!--Solution of Chinese Scrambling with Hot Deployment--> <configuration> <fork>true</fork> <!--increase jvm parameter--> <jvmArguments>-Dfile.encoding=UTF-8</jvmArguments> <!--Specify the entry class--> <mainClass>com.baizhi.Application</mainClass> </configuration> </plugin> </plugins> </build>
15.3 Exclude embedded tomcat
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> <!--Remove embedding tomcat--> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> <!--Remove the use of embedded tomcat analysis jsp--> </dependency>
15.4 Configure the Entry Class
//1. Inherit Spring Boot Servlet Initializer //2. Overlay configure method public class Application extends SpringBootServletInitializer{ public static void main(String[] args) { SpringApplication.run(Application.class,args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(Application.class); } }
15.5 Packaging Test
/* Once deployed using the war package, note: 1. Failure to configure port context-path in application.yml 2. Access projects using the name of the war package and the external tomcat port number */