TheDoctor TheDoctor - 3 months ago 9
Java Question

Use application.properties to initialize an object

I use

@Autowired
in my spring boot application to initialize some properties.
I know how i can initialize primitive datatypes but i don't know how to initialize objects.

That's my
Component
:

@Component
@ConfigurationProperties(prefix = "bitmovin.bitmovin")
public class BitmovinConfig {

private S3InputConfig S3InputConfig = new S3InputConfig();
private int threadPoolSize;
private ArrayList<String> testFiles;

public BitmovinConfig() {
}

public S3InputConfig getS3InputConfig() {
return S3InputConfig;
}

public void setS3InputConfig(S3InputConfig s3InputConfig) {
S3InputConfig = s3InputConfig;
}

public int getThreadPoolSize() {
return threadPoolSize;
}

public void setThreadPoolSize(int threadPoolSize) {
this.threadPoolSize = threadPoolSize;
}

public ArrayList<String> getTestFiles() {
return testFiles;
}

public void setTestFiles(ArrayList<String> testFiles) {
this.testFiles = testFiles;
}
}


And that's my
application.properties
file:

bitmovin.bitmovin.threadPoolSize = 30
bitmovin.bitmovin.S3InputConfig = ??
bitmovin.bitmovin.testFiles= ??


How can i initialize an object or a list in
application.properties
?


UPDATE


The Object, which i didn't create myself, i want to initialize:

public class S3OutputConfig {
@Expose
public String name;
@Expose
public S3Region region;
@Expose
public String accessKey;
@Expose
public String secretKey;
@Expose
public String bucket;
@Expose
public String prefix;
@Expose
public boolean makePublic;
}

Answer

For the list, you have a couple of ways:

bitmovin.bitmovin.testFiles=foo,bar,biz

will set 3 items in testFiles. You can also control things via an index. The code above can be rewritten as

bitmovin.bitmovin.testFiles[0]=foo
bitmovin.bitmovin.testFiles[1]=bar
bitmovin.bitmovin.testFiles[2]=biz

For the object, if you don't create it yourself in the code, you need to make sure it has a public default constructor. Then you navigate your object like any other object, using . to navigate. Assume your S3InputConfig has a name property (with getName and setName):

bitmovin.bitmovin.s3InputConfig.name=the name

You've seen use of lower-case hyphen a lot in Boot's documentation. We support the original format as well as hyphen lower case and others (see relaxed binding). The canonical representation for your config would be as follows:

bitmovin.bitmovin.test-files[0]=foo
bitmovin.bitmovin.test-files[1]=bar
bitmovin.bitmovin.test-files[2]=biz
bitmovin.bitmovin.s3-input-config.name=the name
Comments