I am studing Spring and trying to create bean and pass parameter to it. My bean in Spring configuration file looks like:
@Bean
@Scope("prototype")
public InputFile inputFile (String path)
{
InputFile inputFile = new InputFile();
inputFile.setPath(path);
return inputFile;
}
InputFile class is:
public class InputFile {
String path = null;
public InputFile(String path) {
this.path = path;
}
public InputFile() {
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
and in main method i have:
InputFile inputFile = (InputFile) ctx.getBean("inputFile", "C:\\");
C:\\
- is a parameter which i am trying to pass in.
I run application and receive root exception:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
What i did wrong and how to fix it?
You need to pass a value to your parameter then only you can access the bean. This is what the message given in the Exception.
Use @Value annotation above the method declaration and pass a value to it.
@Bean
@Scope("prototype")
@Value("\\path\\to\\the\\input\\file")
public InputFile inputFile (String path)
{
InputFile inputFile = new InputFile();
inputFile.setPath(path);
return inputFile;
}
Also while accessing this bean you need to access it using the below code
InputFile inputFile = (InputFile) ctx.getBean("inputFile");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With