@SpringBootApplication
// 等價於組合註解:
// @Configuration // 當前類為配置類
// @EnableAutoConfiguration // 啟用自動配置(核心魔法)
// @ComponentScan // 掃描當前包及子包下的 @Component/@Service/@Repository/@Controller
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Component、@Service、@Repository、@Controller、@Configuration 的類自動註冊為 Bean。@ComponentScan(basePackages = "com.example")。在 src/main/resources/META-INF/spring.factories 添加:
org.springframework.context.ApplicationListener=com.example.project.MyListener
Spring 啟動時自動讀取並註冊,無需代碼配置。
@Component
public class StartupRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("應用啟動完成,參數:" + Arrays.toString(args));
// 初始化緩存、啟動定時任務、發送啟動通知等
}
}
CommandLineRunner:接收 String[] argsApplicationRunner:接收 ApplicationArguments(更豐富的參數解析)@Order 排序Spring Boot 按以下順序加載 application.properties/yml,後者覆蓋前者:
/config 子目錄/config支持 Profile 區分:application-dev.properties、application-prod.yml,啟動時 --spring.profiles.active=dev。
請求 /xxx 時,按順序查找:
classpath:/static/classpath:/public/classpath:/resources/classpath:/META-INF/resources/可配置:spring.mvc.static-path-pattern=/assets/**、spring.resources.static-locations=classpath:/custom/。
src/main/resources/templates/hello → 解析為 templates/hello.html| 類型 | 靜態頁面 | 動態模板 |
|---|---|---|
| 位置 | static/error/ | templates/error/ |
| 命名 | 404.html, 5xx.html | 404.ftl, 5xx.ftl |
| 通用 | error.html | error.ftl |