ConfigurationProperties doesn't work when different prefixes and same values are used

user3475366 :

I have the following yaml-property file:

myPrefix: 
  value: Hello
myPrefix2:
  value: World

And two classes

@PropertySource("classpath:permission-config.yml")
@ConfigurationProperties(prefix = "myPrefix")
@Component
@Getter
@Setter
public class ViewUsers {
    private String value;
}

and

@PropertySource("classpath:permission-config.yml")
@ConfigurationProperties(prefix = "myPrefix2")
@Component
@Getter
@Setter
public class ManageUsers {
    private String value;
}

Then null is injected. Or, if I try to use @Value then ONLY latest value is retrieved, which is the last one (World), the preceding ones are always ignored.

Mark Bramnik :

Try the following approach:

  1. Remove @Component from configuration properties (ViewUsers and ManageUsers)
  2. Instead, use the following construction:
@PropertySource("classpath:permission-config.yml")
@ConfigurationProperties(prefix = "myPrefix")
public class ViewUsers {
    private String value; // getter, setter
}

@PropertySource("classpath:permission-config.yml")
@ConfigurationProperties(prefix = "myPrefix2")
public class ManageUsers {
    private String value; // getter, setter
}

@Configuration
@EnableConfigurationProperties({ViewUsers.class, ManageUsers.class}
public class MySampleConfiguration {

    ... beans here...
}

Also make sure that Lombok annotations are working as expected (Try to use without lombok just for the POC).

Update 1

As @M. Deinum has kindly stated, PropertySource like this doesn't work with yaml files.

You can try the following workaround:

@Configuration
@PropertySource(name = "someName", value = "classpath:foo.yaml", factory = YamlPropertySourceFactory.class)
public class MyConfig {
}


import org.springframework.boot.env.YamlPropertySourceLoader;
public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        final List<PropertySource<?>> load = new YamlPropertySourceLoader().load(name, resource.getResource());
        return load.get(0);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=358812&siteId=1