miah
miah

Reputation: 8609

Disabling Spring @Autowired by-name fallback

I have the following classes defined:

public interface Thingy { ... }
public class Foo implements Thingy { ... }
public class Bar implements Thingy { ... }

Classes Foo and Bar are both instanciated as singleton beans with same names, as in

<bean id="foo" class="Foo" />
<bean id="bar" class="Bar" />

The problem happens then trying to autowire field with same name as bean, like

@Autowired
Thingy foo;

Here, field is autowired with Foo instance, and i don't want that. If field name doesn't match bean name, autowiring falis and that's desired. So, is there any way to disable such fallback, so autowiring in above case would fail?

Upvotes: 2

Views: 2001

Answers (3)

Sudhakar
Sudhakar

Reputation: 4873

You can use @Qualifier("beanname") , to ensure you inject it with the correct bean

Upvotes: 0

nicholas.hauschild
nicholas.hauschild

Reputation: 42849

I have a couple suggestions to help you out, although I am not sure exactly what you are asking for is possible.

  1. If you are not using the annotation package-scan functionality for discovering beans, then I think in your spring.xml configuration you can specify your beans to have an autowire detection mode. In the desired bean you specify an element 'autowire', and it has 4 or 5 possible values defined here. I think the one you would want is 'byType'.
  2. You could also look into using the @Qualifier annotation. This is used for when you have multiple beans of the same type in your application context to help distinguish which bean you actually want to use.
  3. Use a different name. Perhaps this is more simple than you were hoping for, but I think it would help to take care of your problem.

Upvotes: 0

abalogh
abalogh

Reputation: 8281

I don't think it's possible, the other way around it is, using setFallbackToDefaultTypeMatch: javadoc: CommonAnnotationBeanPostProcessor

Why don't you just rename either your bean or your class?

Upvotes: 2

Related Questions