The micronaut @EachProperty
allows to drive Bean
(s) creation out of application properties, thus it will create beans (Singleton
POJOs) with properties derived from the nested configuration key / values.
An important note to take into consideration when using @EachProperty
configuration is that it only binds to a top level configuration key i.e. and that the created beans will be named after the nested top higher property which then should be unique.
Your configuration then won't work unless changed to the following:
output:
# Below config will drive a bean named "pdf", more details below
pdf:
size: 50000
# Below config will drive a bean named "docx"
docx:
size: 35000
Note that in above configuration, the name
attribute is omitted as it can be derived from the bean configured name itself:
@EachProperty(value = "output")
public class FileType {
private String name;
private int size;
public FileType(@Parameter("name") String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setSize(int size) {
this.size = size;
}
public int getSize() {
return size;
}
@Override
public String toString() {
return "FileType{" +
"name='" + name + ''' +
", size=" + size +
'}';
}
}
The FileType
constructor will have the configured bean name (derived from the configuration key) injected and the above type will produce two bean at application runtime:
FileType{name='pdf', size=50000}
FileType{name='docx', size=35000}
As those beans are already handled by the micronaut core container, you can have them injected into any other bean.
Otherwise, if you wish to have your beans mapped to a particular configuration format such as a Map [NAME -> SIZE]
, you can:
- Create another
Singleton
bean as a configuration wrapper
- Inject the
FileType
beans
- Map the injected
FileType
beans to your custom format
- Make this custom format accessible your configuration wrapper
Here down a sample configuration wrapper:
@Singleton
public class FileTypeConfiguration {
private final Map<String, Integer> fileTypes;
@Inject
public FileTypeConfiguration(List<FileType> fileTypes) {
this.fileTypes = fileTypes.stream()
.collect(
Collectors.toMap(FileType::getName, FileType::getSize)
);
}
public Map<String, Integer> getFileTypes() {
return fileTypes;
}
}
where you have your configuration accessed through FileTypeConfiguration#getFileTypes
(FileTypeConfiguration
must be @Inject
ed or accessed through ApplicationContext
).