一个关于Spring IoC的简单问题
让我们想象一下,有 1000 个类 (X1...X1000),它们都定义在库 abc.jar
中。
X* 类使用了一些 JSR-330 注释,例如:
class X12 {
@Inject
Foo foo;
@Inject
Bar bar;
}
我的主类是一个测试用例 @RunWith(SpringJUnit4ClassRunner.class)
,以及引用的 Foo
、Bar
在 bean XML 文件中得到了很好的定义。
问题是,我不想在任何 XML 文件中定义 X1...X1000。但我想自动连接它们,例如:
X173 x173 = new X173();
但问题是,使用Java新实例,foo/bar没有连接。
这也不起作用:
X173 x173 = applicationContext.getBean(X173.class);
因为没有定义 X173 的 bean。
并且,X173 还可能包含 X258 类的成员,该成员也应该被连接。在解决这个问题之前我不知道如何实现它。
Let's imagine, there are 1000 classes (X1...X1000) which are all defined in a library abc.jar
.
The X* classes have used some JSR-330 annotations, like:
class X12 {
@Inject
Foo foo;
@Inject
Bar bar;
}
My main class is a test case @RunWith(SpringJUnit4ClassRunner.class)
, and the referenced Foo
, Bar
are well defined in the bean XML files.
The question is, I don't want to define X1...X1000 in any XML files. But I'd like to auto wire them, for example:
X173 x173 = new X173();
But the problem is, using Java new instance, foo/bar isn't wired.
This also not works:
X173 x173 = applicationContext.getBean(X173.class);
because no bean for X173 is defined.
And, X173 may also contains a member of class X258 which should be wired, too. I can't figure out how to implement it until I've resolved this question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 自动检测 将它们声明为 Spring bean。
最明显的方法是使用 Spring 注释(例如
@Component
)来注释这些类,然后将
添加到您的 XML 中。如果注释不是一个选项,
支持可配置的过滤器。例如,如果这些类实际上名为X1...X1000
,则可以使用正则表达式过滤器:You can use autodetection to declare them as Spring beans.
The most obvious way is to annotate these classes with Spring annotations such as
@Component
and then add<context:component-scan />
to your XML.If annotating is not an option,
<context:component-scan />
supports configurable filters. For example, if these classes are actually namedX1...X1000
, you can use regexp filter:好的。有不同类型的测试。让我们也看看其中的一些。
在模块化测试中,您应该测试单个类并模拟它的依赖关系。因此,您应该避免任何注入器。
在集成中,您应该测试某些类的交互,以便您可以像在通常的应用程序中一样使用注入器
Ok. There is different types of testing. Let's look at too of them.
In modular testing you should test single class and mock it's dependency. So, you should avoid any injector.
In integration you should test some class's interaction, so you can use injector as in usual application.