SpringBoot 系列教程(配置文件使用)

本例描述

经过如下范例,能够快速上手使用SpringBoot框架。来一个配置文件使用properties小工程。web

开发工具

本系列教程均采用 IDEA 做为开发工具,JDK 为 1.8spring

测试工具

本例可以使用 PostMan工具来进行测试。PostMan 官网地址 可进行下载。app

开发步骤

  1. 打开IDEA,建立工程 Properties(此处截图省略);
  2. 在POM文件中添加以下代码内容
<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>
  1. 建立包结构信息 com.test.properties.controller(存放控制器代码) 、 com.test.properties.pros(存放属性代码)、com.test.properties.app(存放启动类代码)框架

  2. 建立控制器类 PropertiesController 类,代码以下ide

@RestController
public class PropertiesController {

    @Autowired
    private HomeProperties homeProperties;

    @RequestMapping("/")
    public String sayHomeProperties(){
        return homeProperties.toString();
    }
}

HomeProperties 类为自定义类,下文中会出现spring-boot

  1. 建立属性类 HomeProperties 类,代码以下:
@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属性就会自动关联。工具

  1. 建立启动类 Application 类,代码以下
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  1. 添加属性资源配置文件 在resources目录下新增以下文件: 文件一:application.properties 、文件二:application-dev.properties 文件一中写入以下内容:
## 生产环境配置文件选项
spring.profiles.active=dev

文件二中写入以下内容:post

## config info (生产环境)
home.id=1001
home.name=Test
home.age=25
  1. 启动应用,访问 http://localhost:8080 系统会根据配置文件内容进行反馈。
相关文章
相关标签/搜索