Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: How to inject a String bean to the constructor?

I have a class Config:

Config.java

public class Config {
    private final String p = "Prop";

    @Bean
    public String getP(){return p;}
}

How do I inject this to some constructor, ie:

public class SomeC {
    private String p;

    public SomeC(String p) {
        this. p = p;
    }
}

I want this String p to have injected value from Config. Is that possible?

like image 417
wesleyy Avatar asked Jan 10 '17 14:01

wesleyy


1 Answers

You will have to name the bean, and then use the @Qualifier annotation when autowiring referencing that name.

Example:

Config.java

public class Config {
    private final String p = "Prop";

    @Bean(name="p")
    public String getP(){return p;}
}

SomeC.java

public class SomeC {
    private String p;

    @Autowired
    public SomeC(@Qualifier("p") String p) {
        this. p = p;
    }
}
like image 179
LucasP Avatar answered Nov 09 '22 02:11

LucasP