I have created multimodule project with SpringBoot and Maven.
I have changed application.properties file to application.yml file.
Application.yml file is inside src/main/resources
In service class, I am trying to do
@Value("${keycloak.realm}")
private String REALM;
The first error that I have is:
Could not resolve placeholder 'keycloak.realm' in value "${keycloak.realm}"
When I place @PropertySource(value = "classpath:application.yml") annotation to same service that is calling @Value annotation I am getting following error:
class path resource [application.yml] cannot be opened because it does not exist
Here is service class:
@Slf4j
@Service
@PropertySource(value = "classpath:application.yml")
@RequiredArgsConstructor
public class KeyCloakServiceImpl implements KeyCloakService {
@Value("${keycloak.realm}")
private String REALM;
What am I missing here?
CodePudding user response:
By default, @PropertySource doesn't look for yaml files. To do it, you have to tell @PropertySource to load a yaml file with the factory property :
@PropertySource(value = "classpath:foo.yml", factory = YamlFactory.class)
public class SomeClass() { }
Where an implementation of YamlFactory.class can be :
public class YamlFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource)
throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(encodedResource.getResource());
Properties properties = factory.getObject();
return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
}
}
For more information : https://www.baeldung.com/spring-yaml-propertysource
