spring Sping Boot 中的@Autowired annotation有什么用?

w51jfk4q  于 2024-01-05  发布在  Spring
关注(0)|答案(2)|浏览(196)

我是Sping Boot 的新手。我在Sping Boot 中创建了一个演示REST API。在下面的代码中,即使删除@Autowired annotation,控制器仍然可以工作,我可以调用API。

  1. import com.abhishek.demo2.entity.Question;
  2. import com.abhishek.demo2.service.QuestionService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.*;
  5. import java.util.List;
  6. @RestController
  7. @RequestMapping("/question")
  8. public class QuestionController
  9. {
  10. QuestionService questionService;
  11. @Autowired
  12. public QuestionController(QuestionService questionService)
  13. {
  14. this.questionService = questionService;
  15. }
  16. @GetMapping("/all")
  17. public List<Question> getAllQuestions()
  18. {
  19. return questionService.getAllQuestions();
  20. }
  21. }

字符串
所以,现在我想知道这个@Autowired注解有什么用,它是如何工作的。谢谢。

vmdwslir

vmdwslir1#

在Spring Framework的最新版本中,从版本4.3开始,构造函数注入不再需要@Autowired annotation。如果您的类只有一个构造函数,Sping Boot 会自动注入依赖项,而不需要@Autowired annotation。
这里有一个例子来说明这一点:

  1. @RestController
  2. @RequestMapping("/question")
  3. public class QuestionController
  4. {
  5. QuestionService questionService;
  6. // No @Autowired annotation is needed here
  7. // @Autowired
  8. public QuestionController(QuestionService questionService)
  9. {
  10. this.questionService = questionService;
  11. }
  12. @GetMapping("/all")
  13. public List<Question> getAllQuestions()
  14. {
  15. return questionService.getAllQuestions();
  16. }
  17. }

字符串
在上面的示例中,QuestionService依赖项被自动注入到QuestionController构造函数中,而不需要@Autowired注解。
如果你的类中有多个构造函数,那么你可能需要使用@Autowired annotation来指示Spring应该使用哪个构造函数进行依赖注入。但是,如果你只有一个构造函数,Sping Boot 将执行自动构造函数注入,而不需要@Autowired annotation。

最佳实践

通常,我们会为依赖注入构建一个构造函数,但硬编码的构造函数包含的内容太重,不方便以后修改,所以你可以尝试使用lombokdoc,它是一个库,可以减少简单和复杂的代码,如getter和setter或builder以及实体类的其他基本数据操作。
在netshell中,您可以像下面这样简化代码

  1. @RestController
  2. @RequestMapping("/question")
  3. // add annotation which would build constructor with field type final
  4. @RequiredArgsConstructor
  5. public class QuestionController
  6. {
  7. private final QuestionService questionService;
  8. @GetMapping("/all")
  9. public List<Question> getAllQuestions()
  10. {
  11. return questionService.getAllQuestions();
  12. }
  13. }


Lombok岛的附属国

  1. <dependency>
  2. <groupId>org.projectlombok</groupId>
  3. <artifactId>lombok</artifactId>
  4. <version>1.18.20</version> // replace other version is fine , it according to your java version
  5. </dependency>

展开查看全部
bz4sfanl

bz4sfanl2#

以下是来自spring网站的注意事项-https://docs.spring.io/spring-framework/reference/core/beans/annotation-config/autowired.html
从SpringFramework4.3开始,如果目标bean一开始只定义了一个构造函数,则不再需要在此类构造函数上添加@Autowired注解。但是,如果有多个构造函数可用,并且没有主/默认构造函数,至少有一个构造函数必须用@Autowired进行注解,以便指示容器使用哪个构造函数。请参见关于构造函数解析的讨论有关详细信息

相关问题