Spring Boot 3.自定义配置

自定义配置需要导入以下配置

        <!--自定义配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

配置属性,有多种方式:

第一种是在application.properties中配置,但如果是我们额外的自定义配置的话,是不推荐使用这种方式,在application.properties中一般都是配置Spring Boot的配置

custominapp.name="在application.properties中读取属性值"

编写读取的Bean:prefix 是读取的前缀

package com.example.springbootstudy;

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

@ConfigurationProperties(prefix = "custominapp")
@Component
public class CustomInApp {
    private String name;

    public String getName() {
        return name;
    }

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

第二种方式:

新建cutompro.properties文件

custominpro.name="在custompro.properties读取属性值"

编写读取的Bean:@PropertySource("classpath:/cutompro.properties") 用于指明读取的路径,记住有个 / 斜杆

package com.example.springbootstudy;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@ConfigurationProperties(prefix = "custominpro")
@Component
@PropertySource("classpath:/cutompro.properties")
public class CustomInPro {
    private String name;

    public String getName() {
        return name;
    }

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

测试:

package com.example.springbootstudy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {

    @Autowired
    CustomInApp customInApp;

    @Autowired
    CustomInPro customInPro;

    @GetMapping("custom")
    public String customproperties() {
        return "自定义属性:" + customInApp.getName() + "---" + customInPro.getName();
    }
}

结果:

项目结构:

 

猜你喜欢

转载自www.cnblogs.com/hbolin/p/10659871.html