---
# System prepended metadata

title: '[Spring boot 終極講義]Spring Boot 配置類與XML配置'
tags: [springboot, spring, Java]

---


# [Spring boot 終極講義]Spring Boot 配置類與XML配置

springApplication是Spring Boot提供的一個工具類，它提供了run()方法來啟動Sspring容器來運行Spring Boot。

傳統的Spring都使用XML文件來做為配置問題，但Spring Boot推薦使用Java配置類(帶有@Configuration註解)作為配置文件。

如果希望Spring Boot能家仔其他配置類或著掃描其他包下的配置類或Bean，可以使用如下兩種註解。

* @Import
    該註解顯示指定Spring Boot要加載的配置類。
* @ComponentScan
    該註解指定Spring Boot掃描指定package及其子package下所有的配置類或Bean。
* @ImportResource
    如果專案不可避免要使用到XML配置文件的話，就可以使用這個annotation來導入XML配置文件
    
```
// @SpringBootApplication is a convenience annotation that adds all of the following:
// @Configuration tags the class as a source of bean definitions for the application context.
// @EnableAutoConfiguration tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.
// Normally you would add @EnableWebMvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.
// @ComponentScan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find the controllers.
@SpringBootApplication(scanBasePackages = {"com.example.suipien"})
//@ImportResource is used to import the Spring configuration file(xml).
@ImportResource("classpath:applicationContext.xml")
//@Import is used to import the Spring configuration file(java).
@Import({SpringConfig.class})
public class SuipienApplication {

	public static void main(String[] args) {
		// The SpringApplication.run() method tells Spring to launch an application.
		SpringApplication.run(SuipienApplication.class, args);
	}

}
```



---

###### tags: `java` `spring` `springboot`