1、前言碎語
博主公司一個項目在開發中使用某些功能的時候,受限於spring低版本的限制,故索性將整個模塊升級為spring boot,在這里做個記錄,希望能幫助到有相同場景的朋友。
整個改造過程非常簡單,耗時大概在2個小時左右,主要解決項目中的各種版本沖突,不過下面我會介紹一個神器。
2、老項目情況
1.項目使用spring-context作為容器,使用RabbitMQ提供RPC服務
2.spring.springframework 版本比較低,3.1.x的版本,升級后會變成4.3.x
3.項目使用maven構建
以上是項目的基本情況,針對如上情況,下面會詳細描述改造過程中需要的關注點。
第一步:添加spring boot依賴
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.7.RELEASE</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>
第二步:****新增spring boot啟動類,加載原先的xml配置
/**
* Created by kl on 2018/1/29.
* Content :Lbt-service-ext服務啟動器
*/@SpringBootApplication(exclude = {RabbitAutoConfiguration.class})@ImportResource("service-context.xml")publicclassLbtServiceExtApplication{
publicstaticvoid main(String[] args) {
SpringApplication application= newSpringApplication(LbtServiceExtApplication.class);
application.setWebEnvironment(false);
application.run(args);
}}
注意的地方:
1.排除了RabbitMQ的自動裝載了,因為在xml中已經配置過了RabbitMQ的相關連接和服務信息了
2.設置了setWebEnvironment(false),標記項目為非web項目,因為只是提供RPC服務,所以不需要servlet容器。
第三步:****嘗試啟動,排除jar沖突
這個時候可以啟動main方法,看看能否啟動了,一般情況下沒那么容易就能啟動起來,會有各種的jar沖突。我們項目從3.x到4.x,更是各種沖突。
下面介紹一個插件,破除jar沖突排除的煩惱,前提是在IDEA下開發,eclipse應該也有類似的。
插件名字:****Maven Helper
可以代替mvn dependency:tree命令的使用了,這個插件可以更直觀的列出項目依賴的jar,非常牛逼的是可以直接列出項目中有沖突的jar,這對找jar沖突非常有用,而且可以直接右鍵排除掉。
jar相關異常識別技巧:
出現NoSuchMethodError:一般都是jar沖突了
出現ClassNotFoundException:缺少相關的jar了
三步做完后,項目妥妥的跑起來了。
3、Spring Boot怎么識別web項目
1.spring boot會識別項目是否是web項目,如果識別到事web項目,又沒有添加tomcat等容器jar,就拋異常。
2.識別的方式就是看項目是否依賴了servlet-api和spring-web。而我們項目需要spring-web相關如el等功能又不需要tomcat容器,所以可以指定為非web項目。
3.排除掉tomcat后,項目jar體積和運行時內存占用都有很大的改善。
推薦去我的博客閱讀更多:
2.Spring MVC、Spring Boot、Spring Cloud 系列教程
3.Maven、Git、Eclipse、Intellij IDEA 系列工具教程
覺得不錯,別忘了點贊+轉發哦!