[toc] ### 開始 https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/using-boot-structuring-your-code.html 建議把Main Application Class放在 "跟其他Class相對前的根package" ### <font color="yellow">@SpringBootApplication</font> https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/using-boot-using-springbootapplication-annotation.html 等同於 ``` @EnableAutoConfiguration @ComponentScan @Configuration ``` ### <font color="yellow">@Configuration</font> 是<font color="yellow">@Component</font> 建議做一個主要的單一<font color="yellow">@Configuraion</font> class, 用定義main的class也行。 不一定要把所有<font color="yellow">@Configuration</font>都放到同個class。 可以用<font color="yellow">@Import</font> 來import其他configuration class。 配置类用来定义 Spring 上下文中的 Beans,它们通常包含 <font color="yellow">@Bean</font> 注解的方法,会返回 Spring 管理的对象。 ```java== import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public DataSource dataSource() { // 返回一个 DataSource 实例 return new DataSource(); } } ``` ### <font color="yellow">@EnableAutoConfiguration</font> GPT: 它會根據 類路徑上的依賴(如 Spring MVC、JPA、Thymeleaf 等)來判斷應用需要哪些配置,然後自動加載對應的 Spring Bean。 要在其中一個<font color="yellow">@Configuration</font> class新增一個<font color="yellow">@EnableAutoConfiguration</font> or <font color="yellow">@SpringBootApplication</font> ### Spring Sterotype Annotation https://www.geeksforgeeks.org/spring-stereotype-annotations/ org.springframework.stereotype 下列這些會被自動載入為Spring Bean <font color="yellow">@Component</font> (通用) <font color="yellow">@Service</font> <font color="yellow">@Repository</font> (DAO) 會額外處理資料存取異常 <font color="yellow">@Controller</font> 主要用於 Spring MVC ![image](https://hackmd.io/_uploads/B1uvqDT9yx.png) ### Spring Bean 在 Spring 框架中,Bean 是指由 Spring 容器管理的對象。這些對象通常是應用程式中的 服務(Service)、DAO(Data Access Object) 或 控制器(Controller),並且透過 依賴注入(Dependency Injection, DI) 來進行組合與管理。 ```java== import org.springframework.stereotype.Component; @Component public class MyService { public void doSomething() { System.out.println("執行 MyService"); } } ``` 如果不想用 <font color="yellow">@Component</font>, 也可以用Java Config ```java== import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public MyService myService() { return new MyService(); } } ``` ### <font color="yellow">@Autowired</font> https://ithelp.ithome.com.tw/m/articles/10193601 可以讓Spring自動的把属性需要的對象從Spring容器找出来,並注入给該屬性 ### <font color="yellow">@ComponentScan</font> 掃描當前package及所有子package的 <font color="yellow">@Component</font> class 建議放在<font color="yellow">@Configuration</font>的下面。 ```java== import org.springframework.context.annotation.ComponentScan; @ComponentScan public class AppConfig { } ``` 掃描 com.example.myapp ```java== import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages = "com.example.myapp") public class AppConfig { } ```