Skip to content

Inconsistency between property Injection and setter Injection causes NoUniqueBeanDefinitionException [SPR-14179] #18750

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
spring-projects-issues opened this issue Apr 15, 2016 · 1 comment
Assignees
Labels
status: declined A suggestion or change that we don't feel we should currently apply

Comments

@spring-projects-issues
Copy link
Collaborator

spring-projects-issues commented Apr 15, 2016

Christian Hersevoort opened SPR-14179 and commented

The case is as follows:

Beans:

  • MyParentBean
  • MyChildBeanA implements MyChildBean
  • MyChildBeanB implements MyChildBean

XML configuration:

<bean id="myChildBeanA" class="com.hersevoort.java.test.MyChildBeanA">
</bean>
<bean id="myChildBeanB" class="com.hersevoort.java.test.MyChildBeanB">
</bean>
<bean id="myParentBean" class="com.hersevoort.java.test.MyParentBean">
	<property name="myChild" ref="myChildBeanB"/>
</bean>

Case #1: This works:

public class MyParentBean
{
	private MyChildBean myChild;

	@Inject
	public void setMyChild(MyChildBean myChild)
	{
		this.myChild = myChild;
	}
}

Case #2: This doesn't work:

public class MyParentBean
{
	@Inject
	private MyChildBean myChild;
}

I expect Spring to handle both cases exactly the same, but Case #2 throws an unexpected NoUniqueBeanDefinitionException. (see attachment)

Am I wrong to assume this is a bug?


Affects: 4.2.1, 4.2.5, 4.3 RC1

Attachments:

Issue Links:

@spring-projects-issues
Copy link
Collaborator Author

Juergen Hoeller commented

I'm afraid that this is by design: <property> elements in XML bean definitions specify values for bean properties, going through a JavaBean setter method just like setter injection does. This is completely decoupled from field injection which reflectively populates instance fields directly.

In the end, it's a kind of special feature of setter injection: It allows for overriding through external property values, similar to programmatic calling of a public setter method. Whereas field injection unconditionally operates on (typically) private fields, with no programmatic overriding possible either.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
status: declined A suggestion or change that we don't feel we should currently apply
Projects
None yet
Development

No branches or pull requests

2 participants