sjngm
sjngm

Reputation: 12861

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:

@Autowired
private MessageSource messages;

This will cause an exception when starting the web-app as two MessageSources are found. Obviously I can use a @Qualifier to make it clear to Spring what I want. 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?

Upvotes: 3

Views: 3291

Answers (3)

xilef
xilef

Reputation: 2387

With java config, use @Bean(autowireCandidate = false)

Upvotes: 0

Vadzim
Vadzim

Reputation: 26160

In many cases it could be better to promote one bean with primary="true" or @Primary instead of demoting all other candidates with autowire-candidate="false".

Upvotes: 2

gabuzo
gabuzo

Reputation: 7768

Sure you can add autowire-candidate="false" on the definition of the bean you want to hide.

Upvotes: 7

Related Questions