你的位置:首页 > Java教程

[Java教程]Spring 配置解析之Properties


SpringBoot中的的配置简单属性类支持ConfigurationProperties方式,看一个简单的示例。

 1 @ConfigurationProperties(prefix = "org.dragonfei.demo") 2 public class DemoProperties { 3   private String name; 4   private String password; 5   private String test; 6  7   public String getName() { 8     return name; 9   }10 11   public void setName(String name) {12     this.name = name;13   }14 15   public String getPassword() {16     return password;17   }18 19   public void setPassword(String password) {20     this.password = password;21   }22 23   public String getTest() {24     return test;25   }26 27   public void setTest(String test) {28     this.test = test;29   }30 31   @Override32   public String toString() {33     return "DemoProperties{" +34         "name='" + name + '\'' +35         ", password='" + password + '\'' +36         ", test='" + test + '\'' +37         '}';38   }39 }

定义Properties类

1 org.dragonfei.demo.name=dragonfei2 org.dragonfei.demo.password=password3 org.dragonfei.demo.test=test

添加配置
1 @Configuration2 @EnableConfigurationProperties({DemoProperties.class})3 public class DemoConfiguration {4 }

注入Properties
 1 @RunWith(SpringJUnit4ClassRunner.class) 2 @SpringApplicationConfiguration(classes = DemoConfiguration.class) 3 @EnableAutoConfiguration 4 public class DemoPropertiesTest { 5    6   @Autowired 7   private DemoProperties properties; 8   @Test 9   public void testProperties(){10     System.out.println(properties.toString());11   }12 }

简单单元测试
1 DemoProperties{name='dragonfei', password='password', test='test'}

运行单元测试结果

DemoProperties神奇的注入到Spring容器中了。有没有跟我一样很兴奋,这样的 一大好处,将配置文件的属性以类的形式展现,在需要使用的时候只需要,autowire需要的类就可以了,避免大片重复的的${a.b.c}