Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
304 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...