简体   繁体   English

春季:不包括依赖项的注入

[英]Spring: Excluding injection of dependencies

I know this is possible to exclude classes from a component-scan using exclude-filter . 我知道可以使用exclude-filter从组件扫描中排除类。

The question is if it is possible to exclude the injection of a dependency in a class being injected. 问题是,是否有可能在要注入的类中排除依赖项的注入。

For example, say I have the following class: 例如,说我有以下课程:

@Component
public class ServiceFactory
{
    @Resource
    private Service1 service1;

    @Resource
    private Service2 service2;

...

}

Now I would like to have ServiceFactory injected, service1 injected, but I would like to exclude service2 from the injection. 现在,我想注入ServiceFactory,注入service1,但是我想从注入中排除service2。

Of course I tried the following and it didn't work 我当然尝试了以下方法,但没有用

<context:component-scan base-package="mypackage">
    <context:exclude-filter type="assignable" expression="...Service2" />
</context:component-scan>

In your specific case (where you don't want to inject in unit test, but want to inject in prod, but also don't want to create a dummy bean) you can use the @MockBean annotation 在您的特定情况下(您不想在单元测试中注入,但又想在产品中注入,但又不想创建虚拟bean),可以使用@MockBean批注

I think this is a better solution than to just not inject the bean, becuase that way you avoid NullPointerException 我认为这是比不注入Bean更好的解决方案,因为这样可以避免NullPointerException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM