開始

https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/using-boot-structuring-your-code.html

建議把Main Application Class放在 "跟其他Class相對前的根package"

@SpringBootApplication

https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/using-boot-using-springbootapplication-annotation.html

等同於

@EnableAutoConfiguration
@ComponentScan
@Configuration

@Configuration

@Component

建議做一個主要的單一@Configuraion class, 用定義main的class也行。

不一定要把所有@Configuration都放到同個class。
可以用@Import 來import其他configuration class。

配置类用来定义 Spring 上下文中的 Beans,它们通常包含 @Bean 注解的方法,会返回 Spring 管理的对象。

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public DataSource dataSource() { // 返回一个 DataSource 实例 return new DataSource(); } }

@EnableAutoConfiguration

GPT:
它會根據 類路徑上的依賴(如 Spring MVC、JPA、Thymeleaf 等)來判斷應用需要哪些配置,然後自動加載對應的 Spring Bean。

要在其中一個@Configuration class新增一個@EnableAutoConfiguration or @SpringBootApplication

Spring Sterotype Annotation

https://www.geeksforgeeks.org/spring-stereotype-annotations/

org.springframework.stereotype

下列這些會被自動載入為Spring Bean

@Component (通用)
@Service
@Repository (DAO) 會額外處理資料存取異常
@Controller 主要用於 Spring MVC

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

Spring Bean

在 Spring 框架中,Bean 是指由 Spring 容器管理的對象。這些對象通常是應用程式中的 服務(Service)、DAO(Data Access Object) 或 控制器(Controller),並且透過 依賴注入(Dependency Injection, DI) 來進行組合與管理。

import org.springframework.stereotype.Component; @Component public class MyService { public void doSomething() { System.out.println("執行 MyService"); } }

如果不想用 @Component, 也可以用Java Config

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public MyService myService() { return new MyService(); } }

@Autowired

https://ithelp.ithome.com.tw/m/articles/10193601
可以讓Spring自動的把属性需要的對象從Spring容器找出来,並注入给該屬性

@ComponentScan

掃描當前package及所有子package的 @Component class

建議放在@Configuration的下面。

import org.springframework.context.annotation.ComponentScan; @ComponentScan public class AppConfig { }

掃描 com.example.myapp

import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages = "com.example.myapp") public class AppConfig { }