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

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...