原文链接:Migrating from Spring to Spring Boot
In this article, we're going to take a look at how we can migrate an existing Spring Framework application to a Spring Boot application.
在这篇文章中,我们一直来学习下如何把一个再有Spring框架应用程序转为SpringBoot
Spring Boot is not intended to replace Spring, but to make working with it faster and easier. As a result, most of the changes needed for migrating an application are related to configuration. For the most part, our custom controllers and other components will remain the same.
SpringBoot的出现不是为了替代Spring框架,而是为也能让使用Spring框架开发时更快更简便。因此,做项目迁移所做的最大改变是关于配置的。对大多数存在程序代码和组件来说,这些不需要发动。
Developing with Spring Boot brings several advantages: 使用SpringBoot开发的几个优势如下:
First, we'll need a new set of dependencies. Spring Boot provides convenient starter dependencies, which are dependency descriptors that can bring in all the necessary technology for certain functionality.
首先,一套新的依赖添加规则,SpringBoot提供了更方便的依赖添加方式,即 Starters,这些Starters就是一个依赖描述,可以自动添加它需要的功能的一组依赖。
These have the advantage that you no longer need to specify a version for each dependency, but instead, let the starter manage dependencies for you.
这样做的优势就是,你不需要在为Starter需要的一组依赖库分别指定版本了,它会自动找到适用的依赖库并添加到项目中来。
The quickest way to get started is by adding the spring-boot-starter-parent pom.xml:
开始一个SpringBoot项目最快最便捷是就是在 pom.xml 中添加 spring-boot-starter-parent
org.springframework.boot
spring-boot-starter-parent
1.5.6.RELEASE
This will take care of dependency management.
这个会让依赖库的管理更容易
We'll go through some more starters in the next sections, depending on which functionality we will migrate. For reference, you can find the full list of starters here.
再接下来的几个片断里,我们将会查看几个Starter,而查看哪几个,则是看我们需要迁移哪些功能。当然,你也可以从 here 来找到所有Starters
As a more general note, we will want to remove any explicitly defined dependency version which is also managed by Spring Boot. If not, we may encounter incompatibilities between our defined versions and those used by Boot.
一个小提示,最好在依赖库中不指定所需要的版本,SpringBoot会自动管理这些的。需要非要指定版本,则有可能会遇到版本的兼容性问题。
Each application built using Spring Boot needs to define the main entry point. This is usually a Java class with the main method, annotated with @SpringBootApplication:
SpringBoot的应用程序需要定义一个主入口,通常就是一个使用 @SpringBootApplication 注解标记的Java类中的 main 方法,示例如下:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
The @SpringBootApplication annotation adds the following annotations: 而 @SpringBootApplication 注解会自动启动如下注解的功能:
By default, the @SpringBootApplication annotation scans all classes in the same package or below. Therefore, a convenient package structure could look like this:
默认情况下,@SpringBootApplication注解会扫描所在类的兄弟类及子包中的所有类,所以呢,一个比较便捷的包结构是如下图所示的:
An issue we may encounter has multiple configuration classes which conflict. To avoid this, we have the possibility of filtering the classes which are scanned:
一个可能遇到的问题就是多个配置类冲突,这样的话,就需要排队一些类,示例如下:
@SpringBootAppliaction
@ComponentScan(excludeFilters = { 不扫描 com.baeldung.config 下面的所有类
@ComponentScan.Filter(type = FilterType.REGEX,
pattern = "com.baeldung.config.*")}
)
public class Application {
//...
}
Spring Boot relies heavily on annotations for configuration, but you can still import your existing configuration in both annotation and XML format.
SpringBoot严重依赖于注解的配置,但是呢,它也支持导入已存在的注解和XML格式的配置。
For your existing @Configuration or component classes to be picked up, you have two options: 对于存在的使用 @Configuration 注解标记的类或其它组件类,你有两种导入方式:
To import the classes explicitly, you can use the @ComponentScan or @Import annotations on the main class:
如果要显示的导入这些配置类,可以在主入口类上加入 @ComponentScan 或 @Import 注解
@SpringBootApplication
@ComponentScan(basePackages="com.baeldung.config") 扫描包
@Import(UserRepository.class) 导入具体类
public class Application {
//...
}
The official documentation recommends using annotations over XML configuration. However, if you already have XML files you do not wish to convert to Java configuration, you can still import these using @ImportResource:
官方推荐的是使用注解而非XML格式的配置。不过呢,如果有XML格式文件且不想转弯为Java类的配置,则可以使用 @ImportResource 注解来导入
@SpringBootApplication
@ImportResource("applicationContext.xml") 导入XML配置
public class Application {
//...
}
By default, Spring Boot looks for resource files in one of the following locations: 通常情况下,SpringBoot 会在如下位置来定位资源
To migrate, we can move all our resource files to one of these locations, or we can customize the resource locations by setting the spring.resources.static-locations property:
如果要完成迁移,则需要把我们的资源文件迁移到上面的任意一个路径中就行。或者可以可以迁移到自定义的位置,自定义的位置可以通过 spring.resources.static-locations 属性来设置
spring.resources.static-locations=classpath:/images/,classpath:/jsp/
The framework will automatically load any properties defined in files called application.properties or application.yml placed in one of these locations:
SpringBoot会自动加载在如下位置中名为 application.properties 或 application.yml 的配置文件
To avoid loading properties explicitly, we can move them to a file with this name in one of these locations. For example, into the /resources folder which should be present on the classpath.
为了不用在代码中显示的加载属性文件,可以把它们放到以上目录中存放。例如,可以放到 /resources 文件夹中,这个文件夹内的文件最终会被放到类路径根目录。
We can also automatically load profile-specific properties from files called application-{profile}.properties. 同样可以加载模板型名称的属性文件,如 application-{profile}.properties
Also, a large number of predefined property names are available for configuring different application behaviors. 可以从 predefined property names 查看有关应用程序配置的一系列预定义属性
Each Spring framework module that you use in your application will require slight modifications, mainly relating to the configuration. Let's take a look at some of the most commonly used functionalities. 在Spring中使用的模块迁移到SpringBoot时,都需要做一些轻微的变动,主要是配置方面的。接下来看看一些一些最常用功能的迁移吧
Spring Boot provides a starter for web applications that will bring in all the necessary dependencies. This means we can remove all the web-specific dependencies from the Spring framework and replace them with spring-boot-starter-web:
SpringBoot为Web应用开发提供了一个Starter,它会自动添加所需的依赖。也就是说,我们可以移除在Spring框架中的所有WEB相关依赖,在SpringBoot中只需要添加 spring-boot-starter-web 即可
org.springframework.boot
spring-boot-starter-web
Since Spring Boot attempts to auto-configure an application whenever possible based on the classpath, adding this dependency will result in having the @EnableWebMvc annotation added to the main Application class, as well as setting up a DispatcherServlet bean.
因为SpringBoot总是尽可能的去自动完善应用程序的配置,所以添加上面的Starter相当于在主入口类上加入 @EnableWebMvc 注解,也会注册 DispatcherServlet 实例。
If you had a WebApplicationInitializer class that sets up a DispatcherServlet, this is no longer necessary, nor is the @EnableWebMvc annotation.
因此,不需要创建一个 WebApplicationInitializer的实现类,也不需要再显示的添加@EnableWebMVC注解了
We can, of course, define our beans if we want a custom behavior, and in that case, our beans will be used. 当然了,我们也可以自定义Bean加载来做一些设置,如果这样的话,我们定义的类自然而然会被加载使用。
If we explicitly use the @EnableWebMvc annotation on a @Configuration class, then the MVC auto-configuration will no longer be enabled.
注意,如果我们显示在一个@Configuration注解标记的类上增加@EnableWebMvc注解,那么SpringBoot的自动装配就不起作用了。
Adding the web starter also determines the auto-configuration of the following beans:
添加有关WEB的Starter,也会自动的配置以下Bean
As far as building web pages go, the official documentation recommends not using JSP files and using a template engine instead. Auto-configuration is included for the following template engines: Thymeleaf, Groovy, FreeMarker, Mustache. All we need to do to use one of them is add the specific starter:
就创建WEB页面而言,官方推荐是使用模块引擎解析而非使用传统的JSP文件。SpringBoot包含了几种页面模板引擎,如 Thymeleaf Groovy FreeMarker Mustache,使用它们所要做的就添加对就Starter,添加 Thymeleaf 模板引擎的示例如下:
org.springframework.boot
spring-boot-starter-thymeleaf
The template files should be placed in /resources/templates folder. 当然了,页面文件编写后需要放在 /resources/templates 文件夹中
If we want to continue using JSP files, we need to configure the application so that it can resolve JSPs. For example, if our files are in /webapp/WEB-INF/views, then we need to set the following properties:
不过如果想继续使用JSP文件,做一些配置就可以让程序正确解析了。例如,如果JSP文件在 /webapp/WEB-INF/views 文件夹中,在属性文件中加入以下属性来实现JSP解析加载:
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
Also, we can also run our application using an embedded Tomcat server, which will be auto-configured on port 8080 by adding the spring-boot-starter-tomcat dependency:
可以在程序中内嵌服务应用,如Tomcat,在依赖中加 spring-boot-starter-tomcat 即可,之后访问 8080端口就能访问了
org.springframework.boot
spring-boot-starter-tomcat
Other web servers for which Spring Boot provides auto-configuration are Jetty and Undertow.
SpringBoot也可以配置其它的内嵌服务应用,如 Jetty 和 Undertow
The starter for enabling Spring Security is spring-boot-starter-security:
启用Spring安全模块的Starter是 spring-boot-starter-security,示例如下:
org.springframework.boot
spring-boot-starter-security
By default, this will create a user called “user” with a randomly generated password logged during startup and secure all endpoints with basic authentication. However, we usually want to add our security configuration, which is different than the default.
默认情况下,我们可以创建一个名为 ”user“ 密码随机生成的 用记,这样在启动时使用这样的基础验证来安全访问各个连接点。不过呢,一般都是加入自己的安全验证逻辑,这与默认配置有些不一样
For this reason, we will keep our existing class annotated with @EnableWebSecurity which extends WebSecurityConfigurerAdapter and defines a custom configuration:
因为要加入自己的安全验证逻辑的原因,我们需要在已经存在的安全配置类上添加 @EnableWebSecurity 注解,这个类需要是 WebSecurityConfigurerAdapter 的子类,用于自定义的安全验证配置,代码如下:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// ...
}
Depending on which Spring Data implementation we are using, we will need to add the corresponding starter. For example, for JPA, we can add the spring-boot-starter-data-jpa dependency:
根据使用的数据持久化实现的不同,需要添加不同的Starter,如JPA需要添加 spring-boot-starter-data-jpd,示例如下:
org.springframework.boot
spring-boot-starter-data-jpa
If we want to use an in-memory database, adding the corresponding dependency enabled auto-configuration for databases of type H2, Derby, and HSQLDB.
如果要使用一个基于内存存储的数据库,如H2 Derby 和 HSQLDB,则需要添加相应的依赖
For example, to work with an H2 in-memory database, all we need is the h2 dependency:
例如,使用H2数据库,需要做的就是添加它的依赖,示例如下:
com.h2database
h2
If we want to work with a different database type and configuration, such as a MySQL database, then we need the dependency as well as to define a configuration.
如果需要使用其它数据库,拿MySQL来说吧,就需要添加它的依赖及配置一些参数
For this, we can either keep our DataSource bean definition or make use of pre-defined properties:
为了使用MySQL,要么定义 DataSource编码创建,要么使用预定义的MySQL属性来自动创建
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true
spring.datasource.username=user
spring.datasource.password=pass
Spring Boot will auto-configure Hibernate as the default JPA provider, as well as a transactionManager bean.
SpringBoot默认会配置Hibernate做为默认的JPA与数据库进行连接,也会初始化一个事务管理 TransactionManager 实例。
In this article, we have shown some common scenarios encountered when migrating an existing Spring application to the newer Spring Boot framework.
这篇文章介绍了从Spring迁移到SpringBoot的几种不同程序的场景及需要做的事情,希望对你有所帮助
Overall, your experience when migrating will, of course, be highly dependent on the application you have built.
总之呢,迁移项目的复杂和需要完成的事,是和你的程序所用到的具体模块是很有关系的。
大家关注点赞哈