English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
SpringBoot automatic configuration automatically configures the SpringBoot application based on the jar dependencies we add.
For example, if there is an H2database jar, and we have not manually configured any beans related to the database, then Spring Boot's automatic configuration feature will automatically configure it in the project.
We can enable automatic configuration by using the annotation @EnableAutoConfiguration configuration features. But this annotation is not used because it is wrapped in @SpringBootApplication within the annotation. The @SpringBootApplication annotation is a combination of three annotations: @ComponentScan, @EnableAutoConfiguration,, @Configuration . However, we use the @SpringBootApplication annotation instead of @EnableAutoConfiguration.
@SpringBootApplication = @ComponentScan + @EnableAutoConfiguration + @Configuration
when adding in the project to use spring-<groupId>org.springframework.boot<-boot-web When dependencies are added, Spring Boot's automatic configuration will look for Spring MVC in the classpath and automatically configure it. dispatcherServlet , the default error page, network jar.
Similarly, when we add spring-<groupId>org.springframework.boot<-boot-data-When we see the Spring Boot auto-configuration automatically configure Data Source, Entity Manager.
All auto-configuration logic is in spring-<groupId>org.springframework.boot<-autoconfigure.jar as shown in the figure below.
Based on Spring applications require many configurations. When using Spring MVC, we need to configure dispatcher servlet, view resolver, Web jars The following code shows the typical configuration of the dispatcher servlet in a web application:
</servlet> <servlet-name>dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/todo-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </</servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
Similarly, when we use Hibernate/When using JPA, we need to configure the data source, transaction manager, entity manager factory, and so on.
Configure the data source
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${db.driver}" /> <property name="jdbcUrl" value="${db.url}" /> <property name="user" value="${db.username}" /> <property name="password" value="${db.password}" /> </bean> <jdbc:initialize-database data-source="dataSource"> <jdbc:script location="classpath:config/schema.sql" /> <jdbc:script location="classpath:config/data.sql" /> </jdbc:initialize-database>
Configure the entity manager factory
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory"> <property name="persistenceUnitName" value="hsql_pu" /> <property name="dataSource" ref="dataSource" /> </bean>
Configure the transaction manager
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager"/>
If we do not want to be applied, we can also disable specific auto-configuration classes. We use the annotation @EnableAutoConfiguration exclude properties to disable auto-configuration classes. For example:
import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.jdbc.*; import org.springframework.context.annotation.*; @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) public class MyConfiguration "health","templated":false},"health"}} return "Hello User, have a nice day.";
If the class is not in the classpath, we can use the properties of the @EnableAutoConfiguration annotation excludeName 并指定类的 qualified 名称。我们可以使用属性 spring.autoconfigure.exclude 排除任何数量的自动配置类。
在以下示例中,我们将看到Spring Boot的自动配置功能如何工作。
steps1: 打开spring Initializr https://start.spring.io/.
第2步: start.spring.io .Group Create a Controller class in the package3codebox .
steps3: Name. We provide Provide Artifact spring-<groupId>org.springframework.boot<-autoconfiguration-example .
steps4: Executor Auto-Configuration Example. Spring Web,Spring Data JPA,一个 H2数据库.
steps5: actuator< Click (生成)按钮。当我们单击"生成"按钮时,它会将项目包装在 Jar 文件中,并将其下载到本地系统。
第6步: 提取 Jar文件并将其粘贴到STS工作区中。
steps7: 将项目文件夹导入STS。
Project Folder:-File->Import->Next->选择文件夹spring-<groupId>org.springframework.boot<-autoconfiguration-example->Select Project Folder
导入需要一些时间。
steps8: 在目录中创建名称为 Create a Controller class in the package3codebox.controller 的程序包。文件夹 src/main/java .
steps9: 在包中创建名称为 ControllerDemo 的Controller类。3codebox.controller 。
ControllerDemo.java
DemoRestController.java3codebox.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ControllerDemo "health","templated":false},"health"}} @RequestMapping("/") public String home() "health","templated":false},"health"}} return "home.jsp"; return "Hello User, have a nice day."; return "Hello User, have a nice day.";
steps10: in the folder src/main/java 中创建另一个名为 Create a Controller class in the package3codebox.model 的包。
User.java
DemoRestController.java3codebox.model; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="userdata") public class User "health","templated":false},"health"}} @Id private int id; private String username; public int getId() "health","templated":false},"health"}} return id; return "Hello User, have a nice day."; public void setId(int id) "health","templated":false},"health"}} this.id = id; return "Hello User, have a nice day."; public String getUname() "health","templated":false},"health"}} return username; return "Hello User, have a nice day."; public void setUname(String username) "health","templated":false},"health"}} this.username = username; return "Hello User, have a nice day."; @Override "health","templated":false},"health"}} return \ + id + ", uname=" + username + "]"; return "Hello User, have a nice day."; return "Hello User, have a nice day.";
Now, we need to configure H2database.
steps12: Open application.properties file and configure the following content: port, enable H2Console, data source,, URL.
application.properties
server.port=8085 spring.h2.console.enabled=true spring.datasource.platform=h2 spring.datasource.url=jdbc:h2:mem:w3codebox
steps13: in the folder src/main/resources and create a SQL file.
Right-click on src/main/resources folder->New->File->Provide filename->Select Project Folder
We provided the filename data.sql and insert the following data into it.
data.sql
insert into userdata values(101Tom'); insert into userdata values(102Andrew'); insert into userdata values(103Tony'); insert into userdata values(104Bob'); insert into userdata values(105Sam');
steps14: In src folder, create a file named webapp folder.
steps15: using what we ControllerDemo in the returned name to create a JSP file. In ControllerDemo.java, we returned home.jsp .
home.jsp
<%@page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> body> <form action="addUser"> ID :<br /> <input type="text" name="t1><br /> User name :<br /> <input type="text" name="t2><br /> <input type="submit" value="Add"> </form> </body> </html>
steps16: } SpringBootAutoconfigurationExampleApplication.java file. We can see in the console that our application has been successfully running on port 8085 runs.
steps17: Run http: //localhost: 8085/h2-console/It displays the table we defined in application.properties file. driver class configured in theself JDBC URL as well as the default username sa .
We can also test the connection by clicking the following Test connectionbutton. If the connection is successful, the message is displayed Test successful.
steps18: actuator< connectionbutton. It displays the table we defined in the User.java file userdata structure.
steps19: Execute the following query to view the data we have inserted data.sql data from the file
SELECT * FROM USERDATA;
Let's take a close look at the console. We see TransactionManagement, DispatcherServlet, EntityManagerFactory,, DataSource will be automatically configured as shown in the figure below.
We can find more information about automatic configuration in the following ways: Use the following two methods:
Open debug logging Using Spring Boot ActuatorOpen debug logging
We can do this by application.properties Add properties to debug log files in the above example. Let's implement debug logging. Open application.properties Create a file and add the following properties:
logging.level.org.springframework: DEBUG
Now restart the application. We see that an automatic configuration report is printed in the log. The report includes all automatically configured classes. It is divided into two parts: positive matching, negative matchingas shown in the figure below.
positive matching
negative matching
Spring Boot Actuator
We can also use it in the project Actuator Debugging automatic configuration. We will also add HAL Browserto simplify operations.
Let's create a Spring Boot Actuator example.
steps1: Open Spring Initializr http://start.spring.io 。
steps2: Name. We provide start.spring.io .Group Create a Controller class in the package3com.w
steps3: Name. We provide Provide Artifact ID. We provide
steps4: Executor Auto-Configuration Example. Add Dependencies: , Spring Web
<dependency> web</<groupId> <artifactId>spring-<groupId>org.springframework.boot<-boot-Spring Boot Actuator./artifactId> </dependency> <dependency> web</<groupId> <artifactId>spring-<groupId>org.springframework.boot<-boot-starter/artifactId> </dependency>
steps5: actuator< Click Generate (Generate) button. It will bind all the specifications related to the project to a jar
steps6the file and download it to our local system.: Extract
steps7: Download the jar file.: Use the following steps to import
Project Folder:-File->Import->Existing Maven Project->Next- >Browse->Select Project Folder
>Finish After importing the project, we can find the project in the IDE's Package Explorer
steps8: Part, you can see the following directory structure. Create a Controller class in the package3com.wcodebox. We created a named
DemoRestController. In the Controller, we defined a controller class namedhello( )
which returns a string.
DemoRestController.java3package com.w codebox; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController "health","templated":false},"health"}} public class DemoRestController/@GetMapping(" hello() "health","templated":false},"health"}} public String hello() return "Hello User, have a nice day."; return "Hello User, have a nice day.";
steps9: } ActuatorAutoConfigurationExampleApplication.java file.
steps10: Run http: //localhost: 8080/Open the browser and call the URL hello
. It returns the string specified in the controller. http: //localhost: 8080/actuator Now call the executor URL . It will start the executor to display the following three URLs: self {"path":{"href":"http: , and as shown below.
{"_links":{"self":{"href":"http://localhost:8080/"actuator","templated":false}//localhost:8080/actuator/health","templated":false},"health-"health","templated":false},"health"}}//localhost:8080/actuator/{"path":{"href":"http:/"health","templated":false},"health"}}*"path":"","templated":true},"info":{"href":"http://localhost:8080/actuator/{"info":{"href":"http:
steps11: Open pom.xml file and add HAL Browserdependencies.
<dependency> <groupId>org.springframework.data</<groupId> <artifactId>spring-data-rest-hal-browser</artifactId> </dependency>
steps12: Run again ActuatorAutoConfigurationExampleApplication.java file.
To access the HAL browser, please type http://localhost:8080 In the browser, then press Enter key.
Now we can access the actuator through the HAL browser.
and type in the text box of the resource manager /actuator , then click Go > button.
It shows the relationship with the executor. The most important in the executor is beans .
When we click on the arrow of the bean, it will display all
The following figure shows all the automatically configured beans for more details.