一个关于Spring IoC的简单问题

发布于 2024-10-20 21:55:58 字数 657 浏览 6 评论 0原文

让我们想象一下,有 1000 个类 (X1...X1000),它们都定义在库 abc.jar 中。

X* 类使用了一些 JSR-330 注释,例如:

class X12 {

    @Inject
    Foo foo;

    @Inject
    Bar bar;

}

我的主类是一个测试用例 @RunWith(SpringJUnit4ClassRunner.class),以及引用的 FooBar 在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一身仙ぐ女味 2024-10-27 21:55:58

您可以使用 自动检测 将它们声明为 Spring bean。

最明显的方法是使用 Spring 注释(例如 @Component)来注释这些类,然后将 添加到您的 XML 中。

如果注释不是一个选项, 支持可配置的过滤器。例如,如果这些类实际上名为 X1...X1000,则可以使用正则表达式过滤器:

<context:component-scan base-package="com.example">
     <context:include-filter type="regex" expression="com\.example\.X\d{1,4}"/>
</context:component-scan>

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 named X1...X1000, you can use regexp filter:

<context:component-scan base-package="com.example">
     <context:include-filter type="regex" expression="com\.example\.X\d{1,4}"/>
</context:component-scan>
一刻暧昧 2024-10-27 21:55:58

好的。有不同类型的测试。让我们也看看其中的一些。

  • 在模块化测试中,您应该测试单个类并模拟它的依赖关系。因此,您应该避免任何注入器。

  • 在集成中,您应该测试某些类的交互,以便您可以像在通常的应用程序中一样使用注入器

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文