经过如下范例,能够快速上手使用SpringBoot框架。来一个配置文件使用properties小工程。web
本系列教程均采用 IDEA 做为开发工具,JDK 为 1.8spring
本例可以使用 PostMan工具来进行测试。PostMan 官网地址 可进行下载。app
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> </parent>
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <!-- Junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
建立包结构信息 com.test.properties.controller(存放控制器代码) 、 com.test.properties.pros(存放属性代码)、com.test.properties.app(存放启动类代码)框架
建立控制器类 PropertiesController 类,代码以下ide
@RestController public class PropertiesController { @Autowired private HomeProperties homeProperties; @RequestMapping("/") public String sayHomeProperties(){ return homeProperties.toString(); } }
HomeProperties 类为自定义类,下文中会出现spring-boot
@Component @ConfigurationProperties(prefix = "home") public class HomeProperties { /** * ID */ private int id; /** * NAME */ private String name; /** * AGE */ private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return this.getId() + " " + this.getName() + " " + this.getAge(); } }
注解@ConfigurationProperties,表示读取配置文件前缀会自动进行匹配,本范例中配置为home,当配置文件中出现home开头的属性就会自动和当前类中的属性进行匹配。如属性文件中 home.id ,类中id属性就会自动关联。工具
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
## 生产环境配置文件选项 spring.profiles.active=dev
文件二中写入以下内容:post
## config info (生产环境) home.id=1001 home.name=Test home.age=25