springboot在原有配置文件中添加自定义配置

在实际项目开发中,经常需要使用自定义配置,本文讲解在原有配置文件中添加自定义配置;若直接自定义配置文件,请参考我的另一篇博客springboot添加自定义配置文件

在原有配置文件中添加自定义配置,有两种方式

一、第一种方式

1、自定义配置类

首先,自定义配置类,并添加注解@ConfigurationProperties,代码如下:

package com.che.pri.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties
public class DProperties {

    private String name;

    private String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

}
2、添加yml文件配置

yml文件添加如下内容

name:  ShakeSpeare
age:  112
3、编写controller
package com.che.pri.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/p")
public class PropertiesController {

    @Value("${name}")
    private String name;

    @Value("${age}")
    private String age;

    @RequestMapping(value = "/t")
    public String test() {
        return name+","+age;
    }
}

注意:注解@Value("${name}")可以直接拿到yml配置文件中的配置内容

4、测试

浏览器访问http://localhost:8089/p/t
这里写图片描述
原配置文件中添加自定义配置成功

二、第二种方式

1、在springboot启动类添加@EnableAutoConfiguration注解

在springboot启动类添加@EnableAutoConfiguration注解,开启对自定义配置的支持

package com.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@EnableAutoConfiguration
@SpringBootApplication
public class SpringbootPropertiesApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootPropertiesApplication.class, args);
    }
}
2、编写配置类
package com.demo.bean;

public class User {

    private String name;

    private int age;

    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;
    }

}
3、添加yml配置
name: bob
age: 123
4、编写controller
package com.demo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    @Value("${name}")
    private String name;

    @Value("${age}")
    private int age;

    @RequestMapping("/demo")
    public String demo() {
        return name+age;
    }

}
5、测试

浏览器访问 http://localhost:8080/demo
这里写图片描述

猜你喜欢

转载自blog.csdn.net/wsjzzcbq/article/details/82349107