簡體   English   中英

@Autowired 在 Spring 的類上

[英]@Autowired on classes in Spring

我有一個小問題。 如果該類使用@Component、@Service、@Controller 或@Repository 進行注釋,並且我想注入它的依賴項,我是否需要@Autowired?

@RestController
@RequestMapping(value = "/goods", produces = APPLICATION_JSON_VALUE)
@SuppressWarnings("squid:S4684")
public class UserDeviceRestController implements UserDeviceRestApi {

  private final UserDeviceService userDeviceService;

  public UserDeviceRestController(UserDeviceService userDeviceService) {
    this.userDeviceService = userDeviceService;
  }

這段代碼非常適合我,因為它是 UserDeviceService 中指定的 @Service 注釋。 是因為那個嗎?

如果我有一個沒有這個注釋(粗體)的類,我假設我必須在構造函數/字段/setter中@Autowired然后......那么為什么不在所有可能的依賴注入類之上指定@Component而不是記得@Autowired

謝謝提示

如果您只有一個構造函數,則不需要@Autowired 如果你有多個,你必須告訴 String 應該使用哪個構造函數。 在這種情況下,需要@Autowired

@Autowired 默認使用字段注入。 您不需要為它編寫該構造​​函數或任何 setter。 只需使用您提到的任何注釋即可。 因此,所有這些注釋都將成為類的 bean。 以下是這些注釋的詳細信息。

 @Component is a generic stereotype for any Spring-managed component or bean. 
    @Repository is a stereotype for the persistence layer.
    @Service is a stereotype for the service layer.
    @Controller is a stereotype for the presentation layer (spring-MVC).

從 Spring 4.3 開始,構造函數注入不需要注解。

結帳這篇文章Spring 注入沒有自動裝配注釋

暫無
暫無

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

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