Spring Boot 加载properties配置文件

@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(),"我的主题");
    }
}
上一篇:AngularJS-directive自定义指令与link绑定事件


下一篇:mysql索引失效原理(联合索引失效问题)