1.spring Boot官网:Spring Boot
2. Spring Boot introduction:
Using Spring Boot allows us to quickly create a Spring-based project, and to make this Spring project run, we only need very little configuration
3.Spring Boot advantages:
(1) Spring project running independently
Spring Boot can be run in the form of a jar package. To run a Spring Boot project, we only need to run it through the java -jar xx.jar class. Very convenient.
(2) Embedded Servlet container
Spring Boot can embed Tomcat so that we don't need to deploy the project in the form of a war package.
(3) Provide starter to simplify Maven or gradle configuration
Using Spring or SpringMVC, we need to add a lot of dependencies, and many of these dependencies are fixed. Here, Spring Boot can help us simplify Maven or gradle configuration through starter.
(4) Automatically configure Spring
(5) Application monitoring of quasi-production
(6) No code generation and xml configuration
4.quick start
Take IntelliJ IDEA as an example, create a springboot project
|(1) First create a project, select Spring Initializr when creating, and then Next, as shown below:
(2) Fill in the project information, as shown below:
(3) Fill in the technology used in the project. It is recommended to select the latest stable version for the Spring Boot version above. Just check the Web below, as shown below:
(4) Fill in the project name and click finish:
Note: The system will download the required dependencies when it is created for the first time, which takes a little longer, and will be created quickly every time in the future.
5. Run the project
After the project is successfully created, there will be an entry class of the artifactId+Application naming rule in the root directory of the project, as shown below:
This is the DemoApplication class, which is the entry class of our entire project. This class has a @SpringBootApplication annotation, which is the core annotation of the entire Spring Boot. Its purpose is to enable the automatic configuration of Spring Boot. OK, then I add another @RestController annotation to this class to make it a Controller, and then provide an address conversion method, as follows:
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @RestController @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @RequestMapping(value="/",produces="text/plain;charset=UTF-8") public String index(){ return "Hello String Boot"; } }
Then click the project start button to run, which is this button in IntelliJ:
After the startup is successful, access it in the browser as follows:
6. Detailed explanation
(1) Entry class
Creating a new Project system will help us create an entry class named artifactId+Application. There is a main method in this class, which is the entry method of a standard Java application.
(2) @SpringBootApplication annotation source code
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan( excludeFilters = {@Filter( type = FilterType.CUSTOM, classes = {TypeExcludeFilter.class} )} ) public @interface SpringBootApplication { }
It combines @SpringBootConfiguration, @EnableAutoConfiguration and @ComponentScan. If we do not use @SpringBootApplication in the development process, we can use these three annotations in combination. Among these three annotations, @SpringBootConfiguration is actually the @Configuration annotation mentioned in our previous blogs, indicating that this class is a configuration class, and @EnableAutoConfiguration indicates that Spring Boot is based on the jar package dependency in the classpath for the current project. Automatic configuration, I will not repeat the function of the last @ComponentScan, the only thing to note is that if we use the @SpringBootApplication annotation, the system will scan the entity classes in the same level package and subordinate package of the entry class, so we recommend The location of the entry class is under the package name of the groupId+arctifactID combination.
(3) Turn off specific automatic configuration
The @ComponentScan annotation has a filter. If we only want @SpringBootApplication to scan specific classes instead of all classes, we can turn off automatic configuration, as follows:
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
7.banner
When we start the Spring Boot project, the console will output a startup pattern by default, as follows:
This pattern can be modified by yourself if you need it. The modification method is very simple:
(1) Create a new banner.txt document under src/main/resources
(2) Generate the required characters through the http://patorjk.com/software/taag website, and copy the characters to the txt document created in step 1. For example, here is Hello Sang! Generate characters as follows:
(3) Click the select and copy button in the lower left corner, copy the character to the txt document, and then start the project, at this time the text output by the console will automatically change
(4) Closing the Banner requires us to slightly modify the code in the main method, as follows:
public static void main(String[] args) { SpringApplicationBuilder builder = new SpringApplicationBuilder(Test19SpringBoot2Application.class); //Modify Banner's mode to OFF builder.bannerMode(Banner.Mode.OFF).run(args); }
After this modification, we can't see the Banner when we start the Project again.
8. Spring Boot configuration file
Spring Boot uses a global configuration file application.properties or application.yml, which is placed in the src/main/resources directory. Properties is a common configuration file. Spring Boot not only supports the configuration file of the properties type, but also supports the configuration file of the yaml language. I will take the configuration file of the properties type as an example to see a few cases.
(1) Modify the default port and default access path of Tomcat, the default port of Tomcat is 8080, I will change it to 8081, the default access path is http://localhost:8080 , I will change it to http://localhost:8081/ helloboot , let's see how these two requirements can be achieved through simple configuration.
Very simple, add the following code to the application.properties file:
server.context-path=/helloboot server.port=8081Then start Project again, and you have to access it like this in the browser:
(2) General attribute configuration
With Spring Boot, this job will be much easier, we just need to define the properties in application.properties, and then use @Value injection directly in the code.
product.author=zoe product.name=yllyI have specially set Chinese here, because Chinese will be garbled without special processing. The processing method is to continue to add the following code in application.properties:
server.tomcat.uri-encoding=UTF-8 spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true spring.http.encoding.force=true spring.messages.encoding=UTF-8Then click File -> Settings -> Editor -> File Encodings in IntelliJ IDEA to
set the Default encoding for properties files under Properties Files (*.properties) to UTF-8, and set the tick before Transparent native-to-ascii conversion selected. (Please refer to Springboot's solution to the problem of Chinese garbled characters in IDEA reading the properties configuration file )
Then inject directly into the variable through @Value, as follows:
@Value(value = "${product.author}") private String pAuthor; @Value("${product.name}") private String pName;
Modify the index method to return these values:
@RequestMapping(value = "/",produces = "text/plain;charset=UTF-8") String index(){ return "Hello Spring Boot! The pName is "+pName+";and product Author is "+pAuthor; }
Then visit in the browser, the result is as follows:
(9) Type-safe configuration
When we use the above method in actual projects, the workload is slightly larger, because there are too many values of variables to be injected into each project. In this case, we can use a type-safe configuration method, which is to associate the properties attribute with a Bean Together, it will be more convenient to use. Let's see how this is achieved.
a. Create the file product.properties in the src/main/resources folder
The content of the file is as follows
product.author=zoe product.name=yllySend
b. Create a product Bean and inject the values in the properties file, the code is as follows:
Component @ConfigurationProperties(prefix = "product",locations = "classpath:product.properties") public class ProductBean { private String name; private String author; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
may report an error
spring boot Configuration Annotation Proessor not found in classpath
Solution: solve
c. Add path mapping
在Controller中添加如下代码注入Bean
@Autowired private ProductBean pBean;
添加路径映射:
@RequestMapping("/product") public String book() { return "Hello Spring Boot! The pName is "+pBean.getName()+";and pAuthor is "+pBean.getAuthor(); }
浏览器访问如下:
(10)日志配置
默认情况下Spring Boot使用Logback作为日志框架,也就是我们前面几篇博客中用到的打印日志方式,当然如果有需要我们可以手动配置日志级别以及日志输出位置,相比于我们在Spring容器中写的日志输出代码,这里的配置很简单,只需要在application.properties中添加如下代码:
logging.file=/home/sang/workspace/log.log logging.level.org.springframework.web=debug
上面表示配置日志输出位置,下面配置日志级别。
(11)Profile配置问题
全局Profile配置我们使用application-{profile}.properties来定义,然后在application.properties中通过spring.profiles.active来指定使用哪个Profile。如下例:
a.在src/main/resources文件夹下定义不同环境下的Profile配置文件,文件名分别为application-prod.properties和application-dev.properties,这两个前者表示生产环境下的配置,后者表示开发环境下的配置,如下:
application-prod.properties:
server.port=8081
application-dev.properties:
server.port=8080
然后在application.properties中进行简单配置,如下:
spring.profiles.active=dev
这个表示使用开发环境下的配置。然后运行项目,我们得通过8080端口才可以访问,
产品环境下把spring.profiles.active=dev改成spring.profiles.active=prod 需要通过8081访问