在Spring Boot應用程式專案中,如果要匯入Spring的xml配置檔,可在Spring Boot的Application類別(即啟動Spring Boot的類別)搭配@ImportResource注釋來指定配置檔的位置來匯入。
例如在classpath路徑下有一個applicationContext.xml配置檔。
applicationContext.xml
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@Import(MyConfig.class)
@ImportResource("classpath:applicationContext.xml")
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
@ImportResource的功能類似xml配置檔中的<import/>標籤。
而@ImportResource與@Import的區別是,@Import用來匯入掛有@Configuration的配置類別,例如上面MyApplication類匯入的配置類別MyConfig如下。
MyConfig.java
@Configuration
public class MyConfig {
...
}
若後面classpath:加個星號如classpath*,是指除了classpath下,所有jar的classpath符合指定路徑的配置檔也會一併匯入。classpath:的路徑值為Ant-style patterns,例如classpath:com/abc/**/applicationContext.xml。
沒有留言:
張貼留言