簡體   English   中英

@ Service / @ Controller批注無需使用@Bean批注即可創建新的bean

[英]@Service/@Controller annotations creates a new bean without using @Bean annotation

我有一個用@Service @Scope注釋的類

@Slf4j
@Service
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class ProductDataModel {
@Value("${message}")
private String message;

上面的代碼似乎是為ProductDataModel創建一個bean,而不使用@Bean批注。

我在我的代碼中使用@Autowired ProductDataModel productDataModel ,並且與上述代碼一起使用時,依賴產品productDataModel不為null。

上面的代碼是如何創建bean的?

理想情況下,我希望只有在使用以下代碼時才能創建bean

//I am not using this piece of code in my program., for reference only

@Configuration
public class OSCConfig {

@Bean
 @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
ProductDataModel productDataModel(){
return new ProductDataModel();
}

有人可以解釋兩段代碼以及何時使用哪段代碼的區別。

作為@M。 Deinum指出,當我們聲明@Service或@Controller批注時,如果該容器啟用了組件掃描,則不需要為每個類指定@Bean。

所以使用@Bean的好用例可能是

  • 如果該類在第三方jar中,則不能添加@ Service / @ Controller批注
  • 如果要在@Bean注釋方法中添加一些自定義邏輯

Spring在掃描要創建的對象(作為包掃描的一部分)時會使用@Service批注。 它是spring @Component批注的一種專業化,但是除了向用戶提供有關其預期用途的指示外,沒有做太多其他的事情。 @Controlller批注類似,但是創建的bean具有特定的特征。

創建對象時也會使用@Bean注釋,因為它在創建對象時使用,並且在這種情況下,它位於Configuration類的某個方法上,因此創建的bean具有該方法返回的類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM