@Configuration
@ConfigurationProperties(prefix = "myemail")
@PropertySource(ignoreResourceNotFound = true,value = "classpath:/config/email.properties")
public class EmailConfig {
private String address;
private String port;
private String title;
//getter and setter
}
其中ConfigurationProperties的作用是 bound to structured objects via @ConfigurationProperties
PropertySource和Configuration一起使用,以下是API中的解释
Annotation providing a convenient and declarative mechanism for adding a PropertySource to Spring's Environment. To be used in conjunction with @Configuration classes.(为把属性资源添加到Spring的环境变量中提供一种便捷的声明机制,要配合Configuration注解一起使用)
以下是测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailConfigTest {
@Autowired
private EmailConfig config;
@Test
public void testEmailConfig() {
System.out.println(config.getPort());
System.out.println(config.getAddress());
System.out.println(config.getTitle());
Assert.assertEquals(config.getAddress(),"127.0.0.1");
Assert.assertEquals(config.getPort(),"8088");
Assert.assertEquals(config.getTitle(),"我的主题");
}
}
时间: 2024-10-24 12:23:25