Reputation: 59
if I have the two classes below as we could see this is a constructor injection for SomeBean, however the constructor in SomeBean only has the constructor with parameter "String words", so during the dependency injection how do we specify the parameter for the constructor of the dependency?
@Component
public class SomeBean {
private String words;
public SomeBean(String words) {
this.words = words;
}
public String getWords() {
return words;
}
public void setWords(String words) {
this.words = words;
}
public void sayHello(){
System.out.println(this.words);
}
}
@Service
public class MapService {
private SomeBean someBean;
@Autowired
public MapService(SomeBean someBean) {
this.someBean = someBean;
}
public MapService() {
}
public void sayHello(){
this.someBean.sayHello();
}
}
Upvotes: 0
Views: 523
Reputation: 331
For Java based configuration:
@Configuration
public class SpringAppConfiguration {
@Bean
public SomeBean someBean() {
return new SomeBean("value");
}
}
For XML configuration:
<bean id="someBean" class="package.SomeClass">
<constructor-arg index="0" value="some-value"/>
</bean>
Check this quick guide: https://www.baeldung.com/constructor-injection-in-spring
Upvotes: 1
Reputation: 13
You should add a Bean of the SomeBean type to a Spring configuration class.
Example of such class with the required Bean:
@Configuration
public class Config {
@Bean
public SomeBean someBean() {
return new SomeBean("words");
}
}
Upvotes: 1