May12
May12

Reputation: 2520

No qualifying bean of type [java.lang.String] found for dependency when pass parameter to the Bean

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?

Upvotes: 9

Views: 44163

Answers (1)

Vivek Singh
Vivek Singh

Reputation: 2073

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

Upvotes: 7

Related Questions