1.情况
application.yml中:
server:
port: 8080
address: localhost
在测试类中获取值:serverConfig.getPort()为-1
/**
获取配置类
**/
@Configuration
@Data
@ConfigurationProperties(prefix = "server")
public class ServerConfig {
private int port;
private String address;
}
//测试类中
@RunWith(SpringRunner.class)
@SpringBootTest(classes = D.class)
public class D {
@Autowired
private ServerConfig serverConfig;
@Test
public void getValue(){
System.out.println(serverConfig.getPort()); //为-1
System.out.println(serverConfig.getAddress());
}
}
2.原因以及解决办法
测试类启动springboot程序时并没有以配置端口启动服务,所以我们要以配置端口的方式启动服务,在启动类上添加:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class D {
@Autowired
private ServerConfig serverConfig;
@Test
public void getValue(){
System.out.println(serverConfig.getPort()); //为8080
System.out.println(serverConfig.getAddress());
}
}