I know similar questions have been asked many times with different variations. I have tried to learn from them and from the available tutorials and try to get it working but I think I am missing something that I am not able to figure out.
I want to load a configuration from the external yaml file admin-config.yml
, and not the default application.yml
in my case.
This is what I have done so far.
- Annotated the Application file with
@EnableConfigurationProperties
@SpringBootApplication
@EnableConfigurationProperties
public class MyServer {
public static void main(String[] args) {
SpringApplication.run(MyServer.class, args);
}
}
- The
AdminConfig
component class:
@Component
@PropertySource("classpath:admin-config.yml")
@ConfigurationProperties(prefix = "admin-config")
public class AdminConfig {
private List<PrimeModerator> primeModerators;
@PostConstruct
public void init() {
System.out.println(primeModerators); // this is null
}
public void setPrimeModerators(List<PrimeModerator> primeModerators) {
this.primeModerators = primeModerators;
}
public List<PrimeModerator> getPrimeModerators() {
return primeModerators;
}
}
- The
PrimeModerator
class
@Data
public class PrimeModerator implements Serializable {
private long id;
private String name;
private List<String> roles;
private String details;
private Date created;
}
- The
admin-config.yml
.
admin-config:
primeModerators:
- !!com.mydomain.model.PrimeModerator
id: 1
name: Pawan
roles: [super-admin]
- !!com.mydomain.model.PrimeModerator
id: 2
name: Prashant
roles: [admin, moderator]
I have created a unit test case which always fails (which should not).
@SpringBootTest
@RunWith(SpringRunner.class)
public class AdminConfigTest {
@Autowired
private AdminConfig adminConfig;
@Test
public void testAdminConfig() {
assertNotNull(adminConfig.getPrimeModerators()); // this fails
}
}
I am not sure what I am missing here. Using springboot version 2.2.1.RELEASE
with jdk8.
Thanks for your answers in advance!
from this documentation : Baeldung - Spring
It says : "The Hibernate Validation framework uses standard Java bean getters and setters, so it's important that we declare getters and setters for each of the properties."
Could you please test by adding getters/settest in PrimeModerator ? Did you try with a single simple String value before you nested array ? Good luck...
A github sample on Baeldung in the bottom of page