简体   繁体   English

春天:如何从依赖注入中隐藏bean?

[英]Spring: how to hide bean from dependency injection?

The situation is that I have two different resource bundles, a general one and a more specific one. 情况是我有两个不同的资源包,一个是通用资源包,另一个是更特定资源包。 They don't share any message keys. 他们不共享任何消息密钥。

General one: 一般一:

<bean id="messageSourceGlobal" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="messages/messagesGlobal" />
</bean>

I include the general one in my specific one (different file obviously): 我在我的特定文件中包含了一般文件(显然是不同的文件):

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="messages/messages" />
    <property name="parentMessageSource" ref="messageSourceGlobal" />
</bean>

The Java-code then autowires it: 然后,Java代码自动将其连接:

@Autowired
private MessageSource messages;

This will cause an exception when starting the web-app as two MessageSource s are found. 启动Web应用程序时,这将导致异常,因为找到了两个MessageSource Obviously I can use a @Qualifier to make it clear to Spring what I want. 显然,我可以使用@Qualifier向Spring明确说明我想要的内容。 However, the general resource bundle won't be used alone. 但是,一般资源束不会单独使用。 Therefore, I thought that in this case it would make sense to hide the general resource bundle from dependency injection. 因此,我认为在这种情况下,有必要从依赖注入中隐藏通用资源束。 One benefit would be that others won't run into the "duplicates". 一个好处是其他人不会碰到“重复项”。

Is this possible? 这可能吗? How would I do this? 我该怎么做?

确保可以在要隐藏的bean的定义上添加autowire-candidate="false"

在许多情况下,最好是使用primary =“ true”@Primary升级一个bean,而不是使用autowire-candidate =“ false”降级所有其他候选对象

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

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