3

With following yml

app:
  a:
    prop: aaa
  b:
    prop: bbb
@Component
public abstract class Common {

    @Value("${prop}")
    private String prop;

    @ConfigurationProperties(prefix = "app.a")
    @PropertySource("classpath:app.yml")
    @Component
    public static class A extends Common {
    }

    @ConfigurationProperties(prefix = "app.b")
    @PropertySource("classpath:app.yml")
    @Component
    public static class B extends Common {
    }
}

But those two classes has same value, either for a or b.

How can I solve this?

2
  • Does it work if you bring A and B to the top level?
    – jannis
    Commented Dec 3, 2019 at 12:43
  • @jannis Nope. Moving those inner classes to outer level didn't help.
    – Jin Kwon
    Commented Dec 3, 2019 at 13:25

2 Answers 2

2

I found the problem. Simply. yml doesn't work with PropertySource.

I'm still want to believe I'm wrong.

I changed the .yml file to properties and tried with this.

@PropertySource("classpath:/vendor.properties")
@EnableConfigurationProperties
public abstract class Common {

    @Value("${prop}")
    private String prop;

    @ConfigurationProperties(prefix = "app.a")
    @Component
    public static class A extends Common {
    }

    @ConfigurationProperties(prefix = "app.b")
    @Component
    public static class B extends Common {
    }
}

And it worked.

1

You could use a list for your configuration parameters :

app:
  props: 
    - key: a
      value: aaa

    - key: b
      value: bbb

And retreive your value with a more complex way in a separate bean :

@ConfigurationProperties(prefix = "app")
public class CommonConfiguration {
    List<Prop> props;
    //Getters and setters
    public Prop retreiveSpecificConfiguration(String className) {
        //some kind of logic here
    }

    public static class Prop {
      private String key, value;
      //Getters and setters
    }
}

Inject it in your Common class implementation :

@Autowired
CommonConfiguration config;

Not the answer you're looking for? Browse other questions tagged or ask your own question.