1. 程式人生 > 實用技巧 >Spring Boot中常用註解@Configuration,@Component,@Service,@Controller的區別

Spring Boot中常用註解@Configuration,@Component,@Service,@Controller的區別

之前學習Spring Boot有點囫圇吞棗的意味,沒有細究這些註解間的差異。現在空下來重新回過頭來閱讀官方文件才對這幾個註解有了重新的理解,專門寫下來好供日後查詢翻閱。

@Configuration

指示一個類聲明瞭一個或多個@Bean方法,並且可以由Spring容器進行處理以在執行時為這些bean生成bean定義和服務請求。

 @Configuration
 public class AppConfig {

     @Bean
     public FooService fooService() {
         return new FooService(fooRepository());
     }

     @Bean
     
public FooRepository fooRepository() { return new JdbcFooRepository(dataSource()); } // ... }

FooService呼叫的FooRepository型別物件和fooRepository()方法所返回生成的物件是同一個。因為在執行時會對@Component進行CGLIB動態代理。

@Component

在這個註解中的列也會包含一個或多個@Bean方法。用官網的話來說@Component類中的@Bean方法是lite mode。即不支援bean間引用,以上述程式碼為例,獲得的物件就不再是同一個。

@Service,@Controller和@Component的區別

大致上相同,類比的話就是:@Component是一個人,@Service和@Controller擁有一項特長的人

  • @Service:在處理業務邏輯的時候使用
  • @Controller:處理前端請求,轉發,重定向