SpringBoot 自动装配



SpringBoot 自动装配

SpringBoot自动配置根据我们添加的jar依赖项自动配置SpringBoot应用程序。
例如,如果类路径中存在H2数据库Jar,而我们尚未手动配置任何与数据库相关的bean,则Spring Boot的自动配置功能会在项目中自动对其进行配置。
我们可以启用自动通过使用注解
@EnableAutoConfiguration 配置功能。但是此注解不使用,因为它包装在
@SpringBootApplication 注解内。注解@SpringBootApplication是三个注解的组合:
@ComponentScan,@EnableAutoConfiguration,
@Configuration 。但是,我们使用@SpringBootApplication批注而不是使用@EnableAutoConfiguration。
@SpringBootApplication = @ComponentScan + @EnableAutoConfiguration + @Configuration
当添加
在项目中使用spring-boot-starter-web 依赖项时,Spring Boot自动配置会在类路径中查找Spring MVC。它会自动配置
dispatcherServlet ,默认的
错误页面
网络罐子
类似地,当我们添加spring-boot-starter-data-jpa 依赖关系,我们看到Spring Boot自动配置会自动配置
数据源
实体管理器
所有自动配置逻辑都在
spring-boot-autoconfigure.jar 中实现,如下图所示。

SpringBoot 自动装配_https://bianchenghao6.com_【SpringBoot 教程】_第1张

需要自动配置

基于Spring的应用程序需要很多配置。使用Spring MVC时,我们需要配置
dispatcher servlet,视图解析器,Web jars 。以下代码显示了Web应用程序中调度程序servlet的典型配置:
<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>

类似地,当我们使用Hibernate/JPA时,我们需要配置数据源,事务管理器,实体管理器工厂等等。
配置数据源
<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>

配置实体管理器工厂
<bean
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="persistenceUnitName" value="hsql_pu" />
<property name="dataSource" ref="dataSource" />
</bean>

配置事务管理器
<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"/>

禁用自动配置类

如果我们不想被应用,我们还可以禁用特定的自动配置类。我们使用注解@EnableAutoConfiguration的
exclude 属性来禁用自动配置类。例如:
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 
{
}

如果类不在类路径中,我们可以使用@EnableAutoConfiguration批注的属性
excludeName 并指定类的
qualified 名称。我们可以使用属性
spring.autoconfigure.exclude 排除任何数量的自动配置类。

Spring Boot自动配置示例

在以下示例中,我们将看到Spring Boot的自动配置功能如何工作。
步骤1: 打开spring Initializr https://start.spring.io/。
第2步:
名称。我们提供了
com.lidihuo
步骤3: 提供
工件 ID。我们提供了
spring-boot-autoconfiguration-example
步骤4: 添加依赖项:
Spring Web,Spring Data JPA,一个
H2数据库
步骤5: 单击
Generate (生成)按钮。当我们单击"生成"按钮时,它会将项目包装在
Jar 文件中,并将其下载到本地系统。

SpringBoot 自动装配_https://bianchenghao6.com_【SpringBoot 教程】_第2张

第6步: 提取 Jar文件并将其粘贴到STS工作区中。
步骤7: 将项目文件夹导入STS。
文件->导入->现有Maven项目->浏览->选择文件夹spring-boot-autoconfiguration-example->完成
导入需要一些时间。
步骤8: 在目录中创建名称为
com.lidihuo.controller 的程序包。文件夹
src/main/java
步骤9: 在包中创建名称为
ControllerDemo 的Controller类。 strong> com.lidihuo.controller 。
ControllerDemo.java
package com.lidihuo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ControllerDemo 
{
@RequestMapping("/")
public String home()
{
return "home.jsp";
}
}

步骤10: 在文件夹
src/main/java 中创建另一个名为
com.lidihuo.model 的包。 p>

步骤11: 在包
com.lidihuo.model 中创建一个名称为
User 的类。
User.java
package com.lidihuo.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="userdata")
public class User 
{
@Id
private int id;
private String username;
public int getId() 
{
return id;
}
public void setId(int id) 
{
this.id = id;
}
public String getUname() 
{
return username;
}
public void setUname(String username) 
{
this.username = username;
}
@Override
public String toString() 
{
return "User [id=" + id + ", uname=" + username + "]";
}
}

现在,我们需要配置H2数据库。
步骤12: 打开
application.properties 文件并配置以下内容:
端口,启用H2控制台,数据源,
URL。
application.properties
server.port=8085
spring.h2.console.enabled=true
spring.datasource.plateform=h2
spring.datasource.url=jdbc:h2:mem:lidihuo

步骤13: 在文件夹
src/main/resources中创建一个 SQL 文件。
右键单击src/main/resources文件夹->新建->文件->提供文件名->完成
我们提供了文件名
data.sql 并将以下数据插入其中。
data.sql
insert into userdata values(101,'Tom');
insert into userdata values(102,'Andrew');
insert into userdata values(103,'Tony');
insert into userdata values(104,'Bob');
insert into userdata values(105,'Sam');

步骤14:
src 文件夹中创建一个名称为
webapp 的文件夹。
步骤15: 使用我们在
ControllerDemo 中返回的名称创建一个JSP文件。在ControllerDemo.java中,我们返回了
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>

步骤16: 运行
SpringBootAutoconfigurationExampleApplication.java 文件。我们可以在控制台中看到我们的应用程序已成功在端口
8085 上运行。

SpringBoot 自动装配_https://bianchenghao6.com_【SpringBoot 教程】_第3张

步骤17: 打开浏览器并调用URL
http: //localhost: 8085/h2-console/。它显示了我们在
application.properties 文件中配置的
驱动程序类
JDBC URL ,以及默认的用户名
sa

SpringBoot 自动装配_https://bianchenghao6.com_【SpringBoot 教程】_第4张

我们还可以通过以下方式测试连接点击
测试连接按钮。如果连接成功,则显示消息
测试成功。
步骤18: 单击
连接按钮。它显示了我们在User.java文件中定义的表
userdata 的结构。

SpringBoot 自动装配_https://bianchenghao6.com_【SpringBoot 教程】_第5张

步骤19: 执行以下查询,以查看我们已插入
data.sql 文件中的数据
SELECT * FROM USERDATA;

SpringBoot 自动装配_https://bianchenghao6.com_【SpringBoot 教程】_第6张

让我们仔细看一下控制台。我们看到
TransactionManagement,DispatcherServlet,EntityManagerFactory,
DataSource 会自动配置,如下图所示。

SpringBoot 自动装配_https://bianchenghao6.com_【SpringBoot 教程】_第7张

调试自动配置

我们可以通过以下方法找到有关自动配置的更多信息: 使用以下两种方式:

打开调试日志记录
使用Spring Boot执行器

打开调试日志记录
我们可以通过在
application.properties 中添加属性来调试日志记录文件。让我们在上面的示例中实现调试日志记录。打开
application.properties 文件并添加以下属性:
logging.level.org.springframework: DEBUG

现在重新启动应用程序。我们看到在日志中打印了一个自动配置报告。该报告包括所有自动配置的类。分为两部分:
正向匹配
负向匹配,如下图所示。
正向匹配

SpringBoot 自动装配_https://bianchenghao6.com_【SpringBoot 教程】_第8张

否定匹配

SpringBoot 自动装配_https://bianchenghao6.com_【SpringBoot 教程】_第9张

Spring Boot执行器
我们还可以通过在项目中使用
Actuator 调试自动配置。我们还将添加
HAL浏览器,以简化操作。
让我们创建一个Spring Boot Actuator示例。
步骤1: 打开Spring Initializr http://start.spring.io 。
步骤2: 提供
名称。我们提供了
com.lidihuo。
步骤3: 提供
工件 ID。我们提供了
执行器自动配置示例。
步骤4: 添加依赖项:
Spring Web
Spring Boot Actuator。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

步骤5: 单击
Generate (生成)按钮。它将与项目相关的所有规范绑定到一个
jar 文件中,并将其下载到我们的本地系统中。
步骤6: 提取下载的jar文件。
步骤7: 使用以下步骤导入项目文件夹:
文件->导入->现有Maven项目->下一步->浏览- >选择项目文件夹->完成
导入项目后,我们可以在IDE的
Package Explorer 部分中看到以下目录结构。

SpringBoot 自动装配_https://bianchenghao6.com_【SpringBoot 教程】_第10张

步骤8: 在包中创建Controller类
com.lidihuo。我们创建了一个名为
DemoRestController的控制器类。
在Controller中,我们定义了一个名为
hello( ),它返回一个字符串。
DemoRestController.java
package com.lidihuo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoRestController 
{
@GetMapping("/hello")
public String hello() 
{
return "Hello User, have a nice day.";
}
}

步骤9: 运行
ActuatorAutoConfigurationExampleApplication.java 文件。
步骤10: 打开浏览器并调用URL
http: //localhost: 8080/hello 。它返回我们在控制器中指定的字符串。

SpringBoot 自动装配_https://bianchenghao6.com_【SpringBoot 教程】_第11张

现在调用执行器URL
http: //localhost: 8080/actuator 。它将启动显示以下三个URL的执行器:
self
health
info ,如下所示。
{"_links":{"self":{"href":"http://localhost:8080/actuator","templated":false},"health":{"href":"http://localhost:8080/actuator/health","templated":false},"health-path":{"href":"http://localhost:8080/actuator/health/{*path}","templated":true},"info":{"href":"http://localhost:8080/actuator/info","templated":false}}}

步骤11: 打开
pom.xml 文件并添加
HAL浏览器依赖项。
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-hal-browser</artifactId>
</dependency>

步骤12: 再次,运行
ActuatorAutoConfigurationExampleApplication.java 文件。
要访问HAL浏览器,请键入
http://localhost:8080 在浏览器中,然后按Enter键。

SpringBoot 自动装配_https://bianchenghao6.com_【SpringBoot 教程】_第12张

现在我们可以通过HAL浏览器访问执行器。
在资源管理器的文本框中键入
/actuator ,然后单击
Go >按钮。

SpringBoot 自动装配_https://bianchenghao6.com_【SpringBoot 教程】_第13张

它显示了与执行器。执行器中最重要的是
beans

SpringBoot 自动装配_https://bianchenghao6.com_【SpringBoot 教程】_第14张

当我们单击bean的箭头时,它会显示所有

SpringBoot 自动装配_https://bianchenghao6.com_【SpringBoot 教程】_第15张

以上该图显示了所有自动配置的
beans 的详细信息。


<< Python 语法
Python 变量 >>