Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

spring

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?

like image 570
May12 Avatar asked Dec 24 '15 09:12

May12


1 Answers

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");
like image 149
Vivek Singh Avatar answered Sep 18 '22 18:09

Vivek Singh