Spring 父 bean 发生了什么?
我是 Spring 3 的新手,特别是它奇特的附加注释
我不知道如何拥有一个扩展控制器类 A
的控制器类 B
,其中 A
是通过 xml 文件定义的,具有一些有用的东西 - 例如数据库连接或其他东西。
如果我有一个(抽象)父 bean A
和一个具体 bean B
,并且 B
是一个控制器,并且我正在使用注释自动装配(你知道,
),我可以以某种方式将 B
与 A
联系起来吗?我使用注释吗?鉴于 A
需要放入一些随机的 spring bean,我在哪里定义 A
?
I'm new to Spring 3, and its fancy additional annotations in particular
I have no idea how to have a controller class B
, that extends controller class A
, where A
is defined via the xml files to have something useful - say, a db connection or whatever.
If I have an (abstract) parent bean A
, and a concrete bean B
, and B
is a controller, AND i'm using the annotations-auto-wiring (you know,<context:component-scan base-package="package"/>
), can I somehow tie B
to A
? Do i use annotations? Where do i define A
, given that A
needs to have some random spring bean put into it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 @Shakedown 提到的,在控制器中建立数据库连接是一种不好的做法。我知道这只是一个例子,但我想确保指出这一点。
对于大多数项目来说,使用 Spring 注释,您几乎可以完全摆脱 XML。
通常有一个 AbstractController 类,从中派生出其他具体类。
可以使用 @Autowired 注解将依赖项注入到 Spring 类中。如果您想将依赖项注入到您的 AbstractController 中,而从技术上讲,它不是 Spring 托管类 - 您只需添加
@Component
注释即可使其成为一个托管类。然后您可以在子类中使用该依赖项。
Having a database connection in your controller, as @Shakedown mentions, is a bad practice. I know it's just an example, but I wanted to make sure that was pointed out.
With Spring annotations, you can get away from XML almost completely, for most projects.
It is common to have an
AbstractController
class, from which other concrete classes are derived.Dependencies can be injected into Spring classes using the
@Autowired
annotation. If you want to inject dependencies into your AbstractController, which is not technically a Spring managed class - you can make it one simply by adding the@Component
annotation.You can then use the dependency in your subclasses.
这并不是真正的答案 - 但它是我最终采取的解决方案!它几乎只是扩展了博和斯卡夫曼给出的答案,我只是把它放在这里是为了完整。
给定:
以及
我曾经拥有的地方:
并且
我知道有(dun dun DUUUN):
我
我在 AbstractController 派生的抽象类上不需要 @Component,但我认为你的意思是我需要 @Component,如果 想用abstractController做点什么吗?
This isn't really an answer - but it is the solution for i took in the end! It pretty much just expands on the answer given by Beau and skaffman, I'm just putting it here to be complete.
Given:
and
and where I used to have:
and
I know have (dun dun DUUUN):
and
I didn't need the @Component on my AbstractController-derived abstract class, but I take it you mean i need the @Component if I want to do something with abstractController?