spring_reference/IX. ‘How-to’ guides/74.3. Convert an existing a...

50 lines
3.8 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

### 74.3. 将现有的应用转换为Spring Boot
对于一个非web项目转换为Spring Boot应用很容易抛弃创建ApplicationContext的代码取而代之的是调用SpringApplication或SpringApplicationBuilder。Spring MVC web应用通常先创建一个可部署的war应用然后将它迁移为一个可执行的war或jar。建议阅读[Getting Started Guide on Converting a jar to a war.](http://spring.io/guides/gs/convert-jar-to-war/)。
通过继承SpringBootServletInitializer创建一个可执行war比如在一个名为Application的类中然后添加Spring Boot的`@EnableAutoConfiguration`注解。示例:
```java
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
// Customize the application or call application.sources(...) to add sources
// Since our example is itself a @Configuration class we actually don't
// need to override this method.
return application;
}
}
```
记住不管你往sources放什么东西它仅是一个Spring ApplicationContext正常情况下任何生效的在这里也会起作用。有一些beans你可以先移除然后让Spring Boot提供它的默认实现不过有可能需要先完成一些事情。
静态资源可以移到classpath根目录下的`/public`(或`/static``/resources``/META-INF/resources`)。同样的方式也适合于`messages.properties`Spring Boot在classpath根目录下自动发现这些配置
美妙的Vanilla usage ofSpring DispatcherServlet和Spring Security不需要改变。如果你的应用有其他特性比如使用其他servlets或filters那你可能需要添加一些配置到你的Application上下文中按以下操作替换web.xml的那些元素
- 在容器中安装一个Servlet或ServletRegistrationBean类型的`@Bean`就好像web.xml中的`<servlet/>`和`<servlet-mapping/>`。
- 同样的添加一个Filter或FilterRegistrationBean类型的`@Bean`(类似于`<filter/>`和`<filter-mapping/>`)。
- 在XML文件中的ApplicationContext可以通过`@Import`添加到你的Application中。简单的情况下大量使用注解配置可以在几行内定义`@Bean`定义。
一旦war可以使用我们就通过添加一个main方法到Application来让它可以执行比如
```java
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
```
应用可以划分为多个类别:
- 没有web.xml的Servlet 3.0+应用
- 有web.xml的应用
- 有上下文层次的应用
- 没有上下文层次的应用
所有这些都可以进行适当的转化,但每个可能需要稍微不同的技巧。
Servlet 3.0+的应用转化的相当简单如果它们已经使用Spring Servlet 3.0+初始化器辅助类。通常所有来自一个存在的WebApplicationInitializer的代码可以移到一个SpringBootServletInitializer中。如果一个存在的应用有多个ApplicationContext比如如果它使用AbstractDispatcherServletInitializer那你可以将所有上下文源放进一个单一的SpringApplication。你遇到的主要难题可能是如果那样不能工作那你就要维护上下文层次。参考示例[entry on building a hierarchy](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-build-an-application-context-hierarchy)。一个存在的包含web相关特性的父上下文通常需要分解这样所有的ServletContextAware组件都处于子上下文中。
对于还不是Spring应用的应用来说上面的指南有助于你把应用转换为一个Spring Boot应用但你也可以选择其他方式。