1. Overview
1.概述
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 Framework应用程序迁移到Spring Boot应用程序。
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.
Spring Boot并不是为了取代Spring,而是为了使其工作更快、更容易。因此,迁移应用程序所需的大部分变化都与配置有关。在大多数情况下,我们的自定义控制器和其他组件将保持不变。
Developing with Spring Boot brings several advantages:
使用Spring Boot进行开发会带来几个优势。
- simpler dependency management
- default auto-configuration
- embedded web server
- application metrics and health checks
- advanced externalized configuration
2. Spring Boot Starters
2.Spring靴启动器
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.
首先,我们需要一组新的依赖项。Spring Boot提供了方便的启动器依赖,这是依赖描述符,可以为某些功能带来所有必要的技术。
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.
这些优点是你不再需要为每个依赖关系指定一个版本,而是让启动器为你管理依赖关系。
The quickest way to get started is by adding the spring-boot-starter-parent pom.xml:
最快的方法是通过添加spring-boot-starter-parent pom.xml:开始。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
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.
在接下来的章节中,我们会根据我们要迁移的功能,再去看一些启动器。作为参考,你可以找到完整的启动器列表这里。
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.
一般来说,我们希望删除任何明确定义的、也由Spring Boot管理的依赖版本。否则,我们可能会遇到我们定义的版本与 Boot 使用的版本之间不兼容的情况。
3. Application Entry Point
3.应用程序入口点
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:
使用Spring Boot构建的每个应用程序都需要定义主入口点。这通常是一个带有main方法的Java类,用@SpringBootApplication注释。
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
The @SpringBootApplication annotation adds the following annotations:
@SpringBootApplication注解添加了以下注解。
- @Configuration – which marks the class as a source of bean definitions
- @EnableAutoConfiguration – which tells the framework to add beans based on the dependencies on the classpath automatically
- @ComponentScan – which scans for other configurations and beans in the same package as the Application class or below
By default, the @SpringBootApplication annotation scans all classes in the same package or below. Therefore, a convenient package structure could look like this:
默认情况下,@SpringBootApplication注解会扫描同一包内或以下的所有类。因此,一个方便的包结构可以是这样的。
If your application is a non-web application which creates an ApplicationContext, this code can be removed and replaced with the @SpringBootApplication class above.
如果你的应用程序是一个创建ApplicationContext的非Web应用程序,这段代码可以被删除,用上面的@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 = {
@ComponentScan.Filter(type = FilterType.REGEX,
pattern = "com.baeldung.config.*")})
public class Application {
//...
}
4. Import Configuration and Components
4.导入配置和组件
Spring Boot relies heavily on annotations for configuration, but you can still import your existing configuration in both annotation and XML format.
Spring Boot在很大程度上依赖注释进行配置,但你仍然可以以注释和XML格式导入你现有的配置。
For your existing @Configuration or component classes to be picked up, you have two options:
对于你现有的@Configuration或组件类被拾取,你有两个选择。
- move the existing classes to a package that is the same or below the main Application class package
- import the classes explicitly
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配置。然而,如果你已经有了不希望转换为Java配置的XML文件,你仍然可以使用@ImportResource导入这些文件。
@SpringBootApplication
@ImportResource("applicationContext.xml")
public class Application {
//...
}
5. Migrate Application Resources
5.迁移应用程序资源
By default, Spring Boot looks for resource files in one of the following locations:
默认情况下,Spring Boot会在以下位置寻找资源文件。
- /resources
- /public
- /static
- /META-INF/resources
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/
6. Migrate Application Properties
6.迁移应用程序属性
The framework will automatically load any properties defined in files called application.properties or application.yml placed in one of these locations:
框架将自动加载任何定义在名为application.properties或application.yml的文件中的属性,这些文件放置在这些位置之一。
- a /config subdirectory of the current directory
- the current directory
- a /config directory on the classpath
- the classpath root
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文件夹,这个文件夹应该存在于classpath上。
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.
另外,大量的预定义属性名称可用于配置不同的应用行为。
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框架模块都需要稍作修改,主要与配置有关。让我们来看看一些最常用的功能。
7. Migrate a Spring Web Application
7.迁移一个Spring Web应用程序
7.1. Web Starter
7.1网络启动器
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:
Spring Boot为Web应用程序提供了一个启动器,它将带来所有必要的依赖。这意味着我们可以从Spring框架中移除所有针对Web的依赖,并用spring-boot-starter-web取代它们。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
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.
由于Spring Boot试图尽可能根据classpath自动配置应用程序,因此添加此依赖关系将导致在主Application类中添加@EnableWebMvc注解,以及设置DispatcherServletbean。
If you had a WebApplicationInitializer class that sets up a DispatcherServlet, this is no longer necessary, nor is the @EnableWebMvc annotation.
如果你有一个WebApplicationInitializer类来设置DispatcherServlet,这就不再需要了,@EnableWebMvc注解也是如此。
We can, of course, define our beans if we want a custom behavior, and in that case, our beans will be used.
当然,如果我们想要一个自定义的行为,我们可以定义我们的bean,在这种情况下,我们的bean将被使用。
If we explicitly use the @EnableWebMvc annotation on a @Configuration class, then the MVC auto-configuration will no longer be enabled.
如果我们在@Configuration类上明确使用@EnableWebMvc注解,那么MVC自动配置将不再被启用。
Adding the web starter also determines the auto-configuration of the following beans:
添加网络启动器也决定了以下Bean的自动配置。
- support for serving static content from a directory called /static, /public, /resources or /META-INF/resources on the classpath
- HttpMessageConverter beans for common use cases such as JSON and XML
- a /error mapping that handles all errors
7.2. View Technologies
7.2.查看技术
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:
就构建网页而言,官方文档建议不要使用JSP文件,而是使用模板引擎。自动配置包括以下模板引擎。Thymeleaf, Groovy, FreeMarker, Mustache。我们需要做的就是添加特定的启动器来使用它们中的一个。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
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中,那么我们需要设置以下属性。
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
7.3. Embedded Web Server
7.3.嵌入式网络服务器
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端口。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
Other web servers for which Spring Boot provides auto-configuration are Jetty and Undertow.
Spring Boot提供自动配置的其他Web服务器是Jetty和Undertow。
8. Migrate a Spring Security Application
8.迁移一个Spring安全应用程序
The starter for enabling Spring Security is spring-boot-starter-security:
启用Spring Security的启动器是spring-boot-starter-security。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
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 {
// ...
}
9. Migrate a Spring Data Application
9.迁移一个Spring Data应用程序
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:
根据我们所使用的Spring Data实现,我们将需要添加相应的启动器。例如,对于JPA,我们可以添加spring-boot-starter-data-jpa依赖性。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
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内存数据库,我们只需要h2依赖。
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
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:
为此,我们可以保留我们的DataSourcebean定义,或者利用预定义的属性。
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.
Spring Boot将自动配置Hibernate作为默认JPA提供者,以及transactionManagerbean。
10. Conclusion
10.结论
In this article, we have shown some common scenarios encountered when migrating an existing Spring application to the newer Spring Boot framework.
在本文中,我们展示了将现有Spring应用程序迁移到较新的Spring Boot框架时遇到的一些常见情况。
Overall, your experience when migrating will, of course, be highly dependent on the application you have built.
总的来说,你在迁移时的经验当然会高度依赖于你所建立的应用程序。