COB*_*BOL 5 java spring dependency-injection spring-mvc autowired
我正在使用 Java 和 Spring 开发 Web 应用程序。我是 Spring 的新手,所以作为学习的机会,我基本上得到了一个现有的应用程序,并被告知要扩展它。我无法理解@Autowired 的工作原理。我了解依赖注入的高级概念,但我想知道@Autowired 注释如何知道要注入的接口的具体实现?
为了将我的问题放在上下文中,我将解释我遇到的问题:
我有一个名为PostDao的接口和一个名为PostDaoImpl的类,它实现了PostDao。然后我有另一个名为PostDaoPublicImpl 的类,它扩展了PostDaoImpl。这些类存在于我的持久层中。
然后我有一个名为PostService的接口和一个名为PostServiceImpl的类,它实现了PostService。然后我有另一个名为PostServicePublicImpl 的类,它扩展了PostServiceImpl。这些类存在于我的服务层中。
在PostServiceImpl 中,以下行注入以下对象:
@Autowired private PostDao postDao;
//This injects an object of the class PostDaoImpl
Run Code Online (Sandbox Code Playgroud)
我的问题是,在PostServicePublicImpl 中,我如何具有与上述相同的声明,但让它注入类PostDaoPublicImpl的对象:
@Autowired private PostDao postDao;
//This injects an object of the class PostDaoPublicImpl
Run Code Online (Sandbox Code Playgroud)
我觉得如果我了解 @Autowired 注释的工作原理,那么我就能够解决这个问题。任何解决问题的帮助和建议将不胜感激。
首先你需要了解自动装配是如何工作的
然后在 bean 定义中,定义自动装配策略- 让它成为我们案例的byName
<bean id="postDaoPublicImpl" class="com.yourpackage.PostDaoPublicImpl" autowire="byName" />
Run Code Online (Sandbox Code Playgroud)
这意味着,如果任何类具有名称为“postDaoPublicImpl”的属性(即上述 bean 的 bean id),将自动注入该 bean 实例
之后在你的类中PostServicePublicImpl
定义这样的属性
class PostServicePublicImpl {
@Autowired private PostDaoPublicImpl postDaoPublicImpl;
//here Spring will auto inject PostDaoPublicImpl implementation, since this property name matches the bean id and (auto wiring strategy is "byName")
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14358 次 |
最近记录: |