Reputation: 3021
Lets say i have a class like this :
public class A {
private B b;
public A() {
}
// Some code calling methods in b.
}
How can i inject an instance of B into A via XML configuration without adding a parameterized constructor in Spring ?
Can i have both parameterized constructor and a setter as well ?
public class A {
private B b;
public A(B b) {
this.b = b;
}
public void setB(B b) {
this.b = b;
}
// Some code calling methods in b.
}
Edit : Thanks for all the answers. My actual problem is that i have a class like this :
public class A {
private B b;
public A(B b) {
this.b = b;
}
// Some code calling methods in b.
}
and i want to have a default constructor for the above class without removing the parameterized constructor for backward compatibility reasons.
So ,
Consider that i have an xml file as below :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="name"
class="A">
<constructor-arg ref="B" />
</bean>
</beans>
Upvotes: 0
Views: 1651
Reputation: 17622
You can do it via Setter Injection. For this, you need to add a setter method for your member field b
Can i have both parameterized constructor and a setter as well ?
Yes you can have.
If the parameterized constructor is the only constructor in your bean, then you should go with constructor injection.
else create non-argument default constructor (along with the parameterized constructor) for your class and go with setter OR constructor injection.
Upvotes: 1
Reputation: 11807
The B object cannot be available in the constructor. The best option is to inject it and use a @PostConstruct
method to initialize the bean. To inject the bean b
, setter injection as mentionned by sanbhat. Alternatively, you could also use annotation-based configuration and simply add a @Inject
or @Autowired
annotation to the B field and define your bean B in the XML configuration.
public class A {
@Inject
private B b;
@PostConstruct
public init() {
// inititalization code...
}
// Some code calling methods in b.
}
Upvotes: 0
Reputation: 230
you may pass the bean class B id to Class A via <constructor-arg>
tag like this in (for example beans.xml)
<bean id="a" class="ClassA">
<constructor-arg ref="beanB"/>
</bean>
<bean id="beanB" class="com.tutorialspoint.SpellChecker">
</bean>
the following url may helps you alot in this regard
http://www.tutorialspoint.com/spring/constructor_based_dependency_injection.htm [edited]
Upvotes: 0
Reputation: 136122
If we are not allowed to change this class then there is no way, otherwise we can use Spring's Autowired annotation
public class A {
@Autowired
private B b
...
Upvotes: 0