Spring Boot自定义配置

本文档介绍了如何在Spring Boot项目中创建自定义配置文件,包括新建配置文件、配置类以及在程序中使用这些配置的步骤。通过遵循指南,开发者能够成功地将自定义配置集成到自己的应用中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开发配置:

  • IntelliJ Idea
  • JDK 1.8.0.131 64-bit
  • spring boot 1.5.8

1.新建自定义配置文件

student:
    name: Jack
    age: 16
    score:
        math: 90
        english: 80

yml配置文件

2.新建配置文件对应的类

package com.example.demo.config;

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

@Component
@ConfigurationProperties(prefix = "student")
@PropertySource(value = "classpath:config/my-config.yml",factory=YamlPropertySourceFactory.class)//指定factory
public class Student {
    private String name;
    private Integer age;
    public Score score;

    public  static  class  Score{
        private Integer math;
        private Integer english;

        public Integer getMath() {
            return math;
        }

        public void setMath(Integer math) {
            this.math = math;
        }

        public Integer getEnglish() {
            return english;
        }

        public void setEnglish(Integer english) {
            this.english = english;
        }
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public Score getScore() {
        return score;
    }

    public void setScore(Score score) {
        this.score = score;
    }
}

package com.example.demo.config;

import org.springframework.boot.env.PropertySourcesLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;

public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        return name != null ? new PropertySourcesLoader().load(resource.getResource(), name, null) : new PropertySourcesLoader().load(
                resource.getResource(), getNameForResource(resource.getResource()), null);
    }

    private static String getNameForResource(Resource resource) {
        String name = resource.getDescription();
        if (!org.springframework.util.StringUtils.hasText(name)) {
            name = resource.getClass().getSimpleName() + "@" + System.identityHashCode(resource);
        }
        return name;
    }
}

属性类

3.在程序中使用自定义配置

package com.example.demo.controller;

import com.example.demo.config.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 
 * @author Aaron
 *
 */
@Controller
public class IndexController {
    @Autowired
    private Student student;

    @RequestMapping(value = "/")
    @ResponseBody
    public String getBasicCode() {
        System.out.println("Student name:"+student.getName());
        System.out.println("Student age:"+student.getAge());
        System.out.println("Student score(math):"+student.getScore().getMath());
        System.out.println("Student score(english):"+student.getScore().getEnglish());
        return "index";
    }
}

访问localhost:8080/,Console显示如下:
这里写图片描述

参考:
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#configuration-metadata-annotation-processor


### Spring Boot 自定义配置属性 #### 创建自定义配置类 为了实现自定义配置,在`application.properties`或`application.yml`文件中添加特定前缀的键值对。例如,假设要配置数据库连接池的相关参数: ```properties myapp.datasource.url=jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC myapp.datasource.username=root myapp.datasource.password=password ``` 这些配置项可以通过创建对应的Java配置类来映射并注入到应用程序中[^1]。 #### 添加配置处理器依赖 为了让IDE能够识别来自`.properties`文件中的占位符,并提供更好的开发体验(比如代码补全),可以在项目的`pom.xml`里加入如下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> ``` 此操作有助于提高编码效率以及减少错误的发生概率[^3]。 #### 编写实体类用于接收配置数据 接下来需要构建一个POJO对象用来承载上述配置信息。该类应标注`@ConfigurationProperties(prefix="myapp.datasource")`注解指定其关联的配置项前缀,并通过`@Component`将其注册为Spring容器管理下的bean实例以便后续使用。 ```java import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "myapp.datasource") public class DataSourceConfig { private String url; private String username; private String password; // Getters and Setters } ``` 当应用启动时,框架会自动读取相应的配置并将它们绑定至此类字段上[^2]。 #### 使用自定义配置 最后一步是在业务逻辑层调用已准备好的配置组件。只需简单地将目标Bean注入即可访问其中存储的各项设置值。 ```java @Service public class MyService { @Autowired private DataSourceConfig dataSourceConfig; public void printDataSourceInfo() { System.out.println("Database URL:" + dataSourceConfig.getUrl()); System.out.println("Username:" + dataSourceConfig.getUsername()); System.out.println("Password:" + dataSourceConfig.getPassword()); } } ``` 这样就完成了整个流程——从定义外部化配置直到实际运用的过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值