# Spring使用自定义配置项

***

在写Spring应用的时候，经常会用到Spring支持的application.yml 或 application.properties 来对Spring的一些属性进行设置。

实际上，Spring的这些配置项是与Spring内部的一些bean一一对应的。在配置文件修改这些属性时，就是在修改Spring运行时对应的一些bean的各种属性。

> application.yml 和 application.properties 的区别：
>
> 本质上他们的作用相同，仅仅是格式不同而已。.yml使用yaml格式，用冒号和缩进表示属性、参数以及层级关系；.properties格式用.来作为层级的区分。

基于这种配置项与bean的一一对应关系，我们可以通过Spring提供的注解来使得我们的bean与自定义的配置项挂钩。

为了使得一个模块专注于自己的事而不必兼顾配置项的读取，最好将一个模块需要用到的配置项抽取出来，集合到一个专用于储存配置的类中，比如下面的类`AppConfig`。

```java
package cc.mcyou.jmstest;

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

@Component
@ConfigurationProperties(prefix = "mcyou.config")
@Data
public class AppConfig {
    boolean config1 = true; //默认值
    int config2 = 1;
}
```

注解说明：

* 使用Spring提供的注解`@ConfigurationProperties` 即可告诉Spring应该将这个类纳入配置项管理。属性`prefix`表示在配置项里这个类的属性将在哪个层级下表示。
* 为了使其他类能够使用配置类读取配置项，用`@Component`将其注册为bean。在需要的类处使用`@autowired`引入即可。
* 由于Spring管理配置时都会使用set get等标准bean方法，所以这里必须提供get set方法，否则配置项不生效。这里用lombok的`@Data`。

接下来在对应的.yml或.properties文件里进行配置即可。

```yaml
mcyou:
  config:
    config1: false
    config2: 2
```

除了在这里配置，自定义配置同样可以通过部署环境的环境变量进行调整。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.mcyou.cc/hou-duan-xiang-guan/spring-shi-yong-zi-ding-yi-pei-zhi-xiang.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
