user3475366:
Tengo el siguiente archivo-yaml propiedad:
myPrefix:
value: Hello
myPrefix2:
value: World
Y dos clases
@PropertySource("classpath:permission-config.yml")
@ConfigurationProperties(prefix = "myPrefix")
@Component
@Getter
@Setter
public class ViewUsers {
private String value;
}
y
@PropertySource("classpath:permission-config.yml")
@ConfigurationProperties(prefix = "myPrefix2")
@Component
@Getter
@Setter
public class ManageUsers {
private String value;
}
Entonces nula se inyecta. O, si lo intento de utilizar @Valor entonces sólo se recupera último valor, que es el último (Mundial), los precedentes son siempre ignorados.
Marcos Bramnik:
Pruebe el siguiente enfoque:
- Eliminar
@Component
de las propiedades de configuración (ViewUsers
yManageUsers
) - En su lugar, utilice la siguiente construcción:
@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...
}
También se aseguran de que las anotaciones Lombok están funcionando como se esperaba (Trate de usar sin Lombok sólo por el POC).
actualización 1
Como @M. Deinum ha declarado amablemente, PropertySource como esto no funciona con archivos YAML.
Usted puede probar la siguiente solución:
@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);
}
}