gpt4 book ai didi

java - Spring Framework中使用**@Autowired**注解和接口(interface)声明的一些疑惑

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:57:42 27 4
gpt4 key购买 nike

我是 Spring 框架的新手,我对 @Autowired 注解和接口(interface)声明的使用有一些疑问。

引用这个例子:

http://viralpatel.net/blogs/spring3-mvc-hibernate-maven-tutorial-eclipse-example/

我知道@Autowired 注释可用于自动链接属性上的 bean。

在前面的例子中我有以下情况:

我有一个 ContactDAO 接口(interface),它的实现类名为 ContactDAOImpl

接下来在 ContactServiceImpl 类中有一个使用 @Autowired 注释的变量:

@Autowired
private ContactDAO contactDAO;

我的第一个疑问与 ContactDAO 是一个接口(interface) 的事实有关,所以我在连接什么?具体类型:ContactDAOImpl ?如果是,是 Spring Framework 做的吗?

第二个疑问与spring-servlet.xml 配置文件中没有ContactDAOContactAOImpl< 的bean 定义有关。/strong> 类...为什么?是因为ContactDAOImpl类使用了@Repository注解吗?

谢谢

安德里亚

最佳答案

My first doubt is related to the fact that ContactDAO is an interface so what am I wiring? The concrete type: ContactDAOImpl ? If yes, is the Spring Framework that do it?

只要只有一个匹配的实现,Spring 就会为您 Autowiring 接口(interface)的实现。还有一种方法可以通过使用 @Qualifier@Autowired 并命名实现,将来自多个候选的单个实现与您的 Autowiring 相匹配。

The second doubt is related to the fact that in the spring-servlet.xml configuration file there is not a bean definizion for the ContactDAO orf ContactAOImpl class...why? Is it because ContactDAOImpl class is annoted using @Repository annotation?

如果您使用注解(@Component@Repository@Service@Controller)在您的配置实现中,您不需要在 xml 中显式定义 bean(尽管您也可以这样做)。

编辑:this我的旧答案可能会更清楚地说明在 Spring 中使用注释。

关于java - Spring Framework中使用**@Autowired**注解和接口(interface)声明的一些疑惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15039120/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com