0

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(); } } 
1
  • You will probably need to use an @Bean method to define your SomeBean object. Commented Dec 15, 2020 at 7:35

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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"); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.