Mikhail Geyer
Mikhail Geyer

Reputation: 1171

Is it possible to parse a property from application.yml to the java class field with a different name?

Is it possible to parse a property from application.yml to the java class field with a different name?

Say I have the following application.yml file

service:
  cms:
    webClient: http://www.example.com

and my java class is

@Getter
@Setter
@ConfigurationProperties(prefix = "service.cms")
public class CmsProperties {
  private String webClient;
}

I would like to rename java field name CmsProperties#webClient into CmsProperties#basePath, but I must keep the original name webClient in the application.yml.

Is it possible to do it?

P.S. I am using Spring Framework if it matters for the solution.

Upvotes: 0

Views: 274

Answers (1)

Swarit Agarwal
Swarit Agarwal

Reputation: 2648

OfCourse It is possible.

Spring

When you read property from yml file, you just need to provide key while it stores in basePath

@Value("${webClient}")
private String basePath;

Plain Java

InputStream input = new FileInputStream("path/to/config.properties")) {
Properties prop = new Properties();
prop.load(input);
String basePath = prop.getProperty("webClient")

Hope that does resolve answer

Upvotes: 1

Related Questions