In Spring I can configure all kinds of objects like int, boolean, String, etc. with the @Value injection. I even can configure a whole map structure with a single @Value injection.
Let's assume we have the following TCP server specification class:
public class TcpServerSpec {
private boolean enabled;
private String host;
private int port;
/* getters & setters */
}
I could inject a map of several server specifications by their names, doing ...
@Value("${com.harry.potter.sockets}")
private HashMap<String, TcpServerSpec> sockets;
... with the following YAML configuration (application-test1.yml):
com:
harry:
potter:
sockets:
server1:
enabled: true
host: host1
port: 1111
server2:
enabled: true
host: host2
port: 2222
But often one needs something in between: the injection of just one TcpServerSpec:
@Value("${com.harry.potter.sockets.server1}")
private TcpServerSpec server1;
Then I could pass sucessfully the following tests:
@RunWith(SpringRunner.class)
@SpringBootTest
@ConfigurationProperties("com.harry.potter.sockets")
@TestPropertySource(locations = "classpath:application-test1.yml")
public class MyServerConfiguration1Test {
@Value("${com.harry.potter.sockets.server1}")
private TcpServerSpec server1;
@Value("${com.harry.potter.sockets.server2}")
private TcpServerSpec server2;
@Test
public void testServer1Spec() {
Assert.assertTrue(server1.isEnabled());
Assert.assertThat(server1.getHost(), is("host1"));
Assert.assertThat(server1.getPort(), is(1111));
}
@Test
public void testServer2Spec() {
Assert.assertTrue(server2.isEnabled());
Assert.assertThat(server2.getHost(), is("host2"));
Assert.assertThat(server2.getPort(), is(2222));
}
}
Why is this not possible? Or is it?