我是Sping Boot 的新手。我在Sping Boot 中创建了一个演示REST API。在下面的代码中,即使删除@Autowired
annotation,控制器仍然可以工作,我可以调用API。
import com.abhishek.demo2.entity.Question;
import com.abhishek.demo2.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/question")
public class QuestionController
{
QuestionService questionService;
@Autowired
public QuestionController(QuestionService questionService)
{
this.questionService = questionService;
}
@GetMapping("/all")
public List<Question> getAllQuestions()
{
return questionService.getAllQuestions();
}
}
字符串
所以,现在我想知道这个@Autowired注解有什么用,它是如何工作的。谢谢。
2条答案
按热度按时间vmdwslir1#
在Spring Framework的最新版本中,从版本4.3开始,构造函数注入不再需要@Autowired annotation。如果您的类只有一个构造函数,Sping Boot 会自动注入依赖项,而不需要@Autowired annotation。
这里有一个例子来说明这一点:
字符串
在上面的示例中,
QuestionService
依赖项被自动注入到QuestionController
构造函数中,而不需要@Autowired注解。如果你的类中有多个构造函数,那么你可能需要使用@Autowired annotation来指示Spring应该使用哪个构造函数进行依赖注入。但是,如果你只有一个构造函数,Sping Boot 将执行自动构造函数注入,而不需要@Autowired annotation。
最佳实践
通常,我们会为依赖注入构建一个构造函数,但硬编码的构造函数包含的内容太重,不方便以后修改,所以你可以尝试使用
lombok
doc,它是一个库,可以减少简单和复杂的代码,如getter和setter或builder以及实体类的其他基本数据操作。在netshell中,您可以像下面这样简化代码
型
Lombok岛的附属国
型
bz4sfanl2#
以下是来自spring网站的注意事项-https://docs.spring.io/spring-framework/reference/core/beans/annotation-config/autowired.html
从SpringFramework4.3开始,如果目标bean一开始只定义了一个构造函数,则不再需要在此类构造函数上添加
@Autowired
注解。但是,如果有多个构造函数可用,并且没有主/默认构造函数,至少有一个构造函数必须用@Autowired
进行注解,以便指示容器使用哪个构造函数。请参见关于构造函数解析的讨论有关详细信息