Câu hỏi phỏng vấn Spring
Câu hỏi

What is the difference between @Inject and @Autowired in...

Câu trả lời

The @Inject and @Autowired annotations in Spring Framework are both used for dependency injection, which is a design pattern that allows for loose coupling between classes and their dependencies. However, there are some differences between the two annotations, as well as different scenarios in which one might be preferred over the other.

@Autowired

  • Part of Spring Framework: The @Autowired annotation is specific to the Spring Framework and is defined in the org.springframework.beans.factory.annotation package[1][3].
  • Required Attribute: It has a required attribute that can be set to false to indicate that the dependency is not mandatory. If no matching bean is found and required is set to true, an exception will be thrown during the autowiring process[1][3].
  • Autowiring by Type: By default, @Autowired performs dependency injection by type. If there are multiple beans of the same type, it can lead to ambiguity, which can be resolved using the @Qualifier annotation[6].
  • Tightly Coupled with Spring: Using @Autowired makes your application tightly coupled with the Spring framework. If you plan to switch to another dependency injection framework in the future, you might need to reconfigure your application[3].

@Inject

  • Standard Java Annotation: @Inject is part of the Java CDI (Contexts and Dependency Injection) and is defined by the JSR-330 standard. It is included in the javax.inject package and was introduced in Java 6[1][3].
  • No Required Attribute: Unlike @Autowired, @Inject does not have a required attribute. If a suitable bean cannot be found, the injection will fail, and an exception will be thrown[1].
  • Framework Agnostic: Since @Inject is a standard annotation, it makes your application less dependent on the Spring framework. This means that if you switch to another dependency injection framework that supports JSR-330, such as Google Guice, your beans declared with @Inject will still work[2][5].

Which One to Use and When?

  • **...
expert

expert

Gợi ý câu hỏi phỏng vấn

middle

How to handle exceptions in Spring MVC Framework?

senior

What is reactive programming?

middle

What is the purpose of the session scope?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào