Home > database >  Not able to pass String to a constructor in Java using Spring
Not able to pass String to a constructor in Java using Spring

Time:10-17

I'm trying to pass parameter to one of constructor of my BBFilter component, however it throws the exception that No beans of String type found. I have autowired the constructor as well. Am I doing anything wrong? Please advise

@Bean
public MyBean bbFilter() {
 
    BBBean bbBean = new BBBean();
    bbBean.setFilter(new BBFilter("plan1"));

}

BBFilter

@Component
public class BBFilter implements Filter {

    private String planType;
 
    @Autowired
    public BBFilter(String planType) {    --> Could not autowire. No beans of String type found 
        this.planType = planType;
    }

}

CodePudding user response:

I am assuming you are using Spring. The @Component annotation tells spring to automatically create an Instance of BBFilter as a Bean.

You also annotated the constructor with @Autowired. So Spring searches it's beans for fitting types and injects the automatically on construction. Since you probably didn't define any String bean it cannot autowire the String and throws an exception.

But since you want to create the Filter manually anyways you can simply remove both annotations from your BBFilter Class:

public class BBFilter implements Filter {

    private String planType;

    public BBFilter(String planType) {
        this.planType = planType;
    }

}

This should fix the exception but you also can no longer inject it anywhere else (per @Autowire) if needed.

CodePudding user response:

Declare bean of BBFilter like

@Bean
public BBFilter bbFilter() {
    return new BBFilter("plan1");

}

And use it in BBBean like this

@Bean
public MyBean bbFilter() {
 
    BBBean bbBean = new BBBean();
    bbBean.setFilter(bbFilter());

}

And remove @Component and @Autowired from BBFilter

  • Related