SpringBoot實踐-匯入jar包中的配置檔案
事件起因:開發的專案需要依賴一個本地jar包,無法通過maven直接下載;而這個jar包中含有配置檔案,在配置檔案中定義了spring的bean,而我的專案需要用到這個bean。
開發工具:IDEA
JDK版本:1.7
使用框架:SpringBoot、SpringMVC
解決過程:
1、首先需要在專案中引入這個本地的jar包,而且還要保持maven的pom.xml檔案的一致與整潔。maven提供了一種方案來引入本地jar包,而不是從倉庫下載。當然,也可以自己建立一個maven私服,將jar包上傳到私服倉庫,然後共享給大家,但是有點麻煩。現在來描述第一種思路。
(1)在專案的根目錄下新建一個libs目錄,跟src目錄平級;然後將jar複製到libs目錄。
(2)在pom.xml檔案中新增依賴,如下:
<dependency>
<groupId>com.credit</groupId>
<artifactId>xx</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/xx-1.0.0.jar</systemPath>
</dependency>
因為是本地jar包,所以座標(groupId、artifactId和version)可以隨便寫,最重要的是後面兩個屬性scope和systemPath,scope的值必須是system,表明是外部jar包(scope更多介紹參見
(3)新增依賴之後,還需要新增幾個引數以便在打包的時候能將本地的這幾個jar包包括進去,不然執行的時候會報錯,說找不到這個jar包,我也是後來發現的:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
</plugins>
</build>
核心就是這個includeSystemScope引數。
2、有了jar之後,就有了xml檔案,現在需要在程式碼中引用定義在xml中的bean,如下:
private static IEventPublisher eventPublisher;
@Autowired
public void setEventPublisher(IEventPublisher eventPublisher) {
EmailUtil.eventPublisher = eventPublisher;
}
順便提一下,我這邊需要將這個bean引用設定為static的,這是spring框架的其中一種注入靜態變數的方式,更多方式參見
這裡。
然而,編譯器卻提示我“Could not autowire. No beans of 'IEventPublisher' type found”。那麼顯然了,xml檔案沒有被載入,或者無法讀取到。於是我就想盡各種辦法讓spring去讀取這個位於jar包中的xml:
(1)使用@ImportResource註解,然而並沒有什麼卵用。況且還有一個問題,這個xml的路徑怎麼去寫?這樣:
@ImportResource(value = "classpath*:xx.xml")
那是不行滴。
(2)為什麼不行?是不是因為maven打包的時候沒有把資原始檔加進去?於是我按照往上眾多教程開始鼓搗pom.xml檔案:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerArguments>
<extdirs>${project.basedir}/libs</extdirs>
</compilerArguments>
</configuration>
</plugin>
</plugins>
</build>
仍舊不行。根據我的判斷,
@ImportResource註解只能匯入專案根目錄下的配置檔案,但是對jar包中的檔案是無能為力的。
(3)於是我想到了springboot是鼓勵去xml化的,所以只能廢棄掉原來的xml,而在專案內部以springBoot的方式重建這個xml的內容:
@Configuration
public class Config {
@Bean(name = "emailEventPublisher")
public IEventPublisher eventPublisher() {
EmailEventPublisher eventPublisher = new EmailEventPublisher();
eventPublisher.setJmsTemplate(jmsTemplate());
eventPublisher.setDestination(activeMQQueue());
return eventPublisher;
}
}
就這樣,搞定了。看著簡單,可是費了我兩天時間。。看來還需要繼續深化對maven、spring、springboot的研究。