配置文件,怎么读??

在用.NET 做机房系统时,遇到了配置文件.config文件,不太懂什么意思,就照葫芦画瓢,自己建立一个.config文件来存放自己的东西,可是到了实现阶段,出问题了,我的配置文件,没有被读取。

经过各种实践,终于把我自定义的配置文件里的参数放到系统默认的app.config文件中,就可以用了。

以为,一个项目只可以有一个配置文件,可是为什么我的其他程序集中也可以建立.config 文件呢??

 有很多人在使用config文件都是直接使用appSetting的,把所有的配置参数全都塞到那里,这样做虽然不错,但是如果参数过多,这种做法的缺点也会明显地暴露出来:appSetting中的配置参数项只能按key名来访问,不能支持复杂的层次节点也不支持强类型,而且由于全都只使用这一个集合,你会发现:完全不相干的参数也要放在一起!在网上搜到了一些方法

自定义配置节点

首先,我们来看一下如何在app.config中增加一个自定义的配置节点。最终的配置文件如下:

 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="MySection111" type="RwConfigDemo.MySection1, RwConfigDemo" />
        <section name="MySection222" type="RwConfigDemo.MySection2, RwConfigDemo" />
        <section name="MySection333" type="RwConfigDemo.MySection3, RwConfigDemo" />
        <section name="MySection444" type="RwConfigDemo.MySection4, RwConfigDemo" />
    </configSections>

    <MySection111 username="fish-li" url="http://www.cnblogs.com/fish-li/"></MySection111>

    <MySection222>
        <users username="fish" password="liqifeng"></users>
    </MySection222>

    <MySection444>
        <add key="aa" value="11111"></add>
        <add key="bb" value="22222"></add>
        <add key="cc" value="33333"></add>
    </MySection444>

    <MySection333>
        <Command1>
            <![CDATA[
                create procedure ChangeProductQuantity(
                    @ProductID int,
                    @Quantity int
                )
                as
                update Products set Quantity = @Quantity 
                where ProductID = @ProductID;
            ]]>
        </Command1>
        <Command2>
            <![CDATA[
                create procedure DeleteCategory(
                    @CategoryID int
                )
                as
                delete from Categories
                where CategoryID = @CategoryID;
            ]]>
        </Command2>
    </MySection333>    
</configuration>


自定义配置文件 

又说回来,我自定义的配置文件为什么么有被读取,这就涉及到了文件的读取了。

如果我们不给程序设定路径的话,默认读取的系统的app.config 文件,所以我们自定义的配置文件没有被读取。

要想让自己的配置文件被读取,就需要设置文件的读取路径。

.net有一个ConfigurationManager类可以方面的读取默认的配置文件,如果要读取自定义配置文件,这个类也提供了方法,如下所示:

var configMap = new ExeConfigurationFileMap { ExeConfigFilename = configFile };
   var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
   var configurationSection = config.GetSection(sectionName);

 

配置文件的种类

其实配置文件不一定就是.config 。 也可以用一个记事本,或者是XML 来写。只要我们给出合理的读取路径,就可以把我们需要的信息读取进去。(未完,待续)

 详细博文地址http://wyx-921.blog.163.com/blog/static/197369279201312894216590/

 

<think>我们正在讨论Spring Boot中自定义@Value配置文件路径的方法。根据之前的引用和讨论,关键点在于使用@PropertySource注解指定自定义配置文件的位置,并结合@Value或@ConfigurationProperties来注入值。 注意:在Spring Boot中,默认的配置文件是application.properties或application.yml。但有时我们需要使用额外的配置文件,这时就需要自定义路径。 根据引用[1]和引用[3]中的示例,我们可以通过以下步骤实现: 1. 使用@PropertySource注解标注在配置类上,指定配置文件的路径(可以是classpath下的文件,也可以是文件系统中的绝对路径)。 2. 在类中使用@Value注解注入具体的属性值。 但是,需要注意的是: - 如果使用.yml配置文件,@PropertySource默认不支持,需要额外处理(如使用YamlPropertySourceLoader,但Spring Boot并不直接支持在@PropertySource中加载YAML)。 - 因此,通常建议自定义配置文件使用.properties格式。 另外,引用[2]提到,当使用多个配置文件时(如多环境配置),可以通过spring.profiles.active指定激活的配置文件,但这通常用于application-{profile}.properties的命名约定,而不是自定义的配置文件。 所以,针对自定义配置文件(非application.properties)的路径指定,我们可以这样做: 示例1:使用.properties文件 - 在src/main/resources下创建config.properties文件(或者放在其他位置,如文件系统路径) - 在配置类上使用@PropertySource指定该文件 代码示例: ```java @Component @PropertySource("classpath:config.properties") // 或者使用文件系统路径,如:@PropertySource("file:/path/to/config.properties") public class MyConfig { @Value("${custom.property}") private String customProperty; // getter and setter } ``` 示例2:如果一定要使用YAML文件,则需要自定义PropertySourceFactory,因为默认的PropertySourceFactory只支持properties文件。我们可以这样做: 步骤: 1. 创建一个实现PropertySourceFactory接口的类,用于加载YAML文件。 2. 在@PropertySource中使用factory属性指定这个工厂类。 自定义YAML属性源工厂类: ```java import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.env.PropertySource; import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.PropertySourceFactory; import java.io.IOException; import java.util.List; public class YamlPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource()); return sources.get(0); } } ``` 然后在配置类中使用: ```java @Component @PropertySource(value = "classpath:myconfig.yml", factory = YamlPropertySourceFactory.class) public class MyYamlConfig { @Value("${test}") private String test; // getter and setter } ``` 但是,这种方法有一个缺点:每个@PropertySource只能加载一个YAML文档(因为YAML支持多文档,但这里我们只取第一个)。对于复杂的多文档YAML,可能需要更复杂的处理。 另外,引用[4]展示了在application.properties中设置属性,然后在代码中通过@Value注入。如果自定义配置文件中的属性与application.properties中的属性同名,则默认情况下,application.properties中的属性会覆盖自定义配置文件中的属性(因为application.properties是默认配置文件,优先级较高)。可以通过设置spring.config.name和spring.config.location来改变默认配置文件的名称和位置,但这会影响整个应用。 如果只是添加额外的配置文件,而不改变默认配置,使用@PropertySource是更合适的方式。 总结: 在Spring Boot中自定义@Value配置文件路径的方法: 1. 对于.properties文件:直接使用@PropertySource注解指定文件路径(classpath或文件系统)。 2. 对于.yml/.yaml文件:需要自定义PropertySourceFactory,并在@PropertySource中通过factory属性指定。 注意事项: - 确保配置文件在指定路径下存在。 - 在配置类上添加@Component(或其他Spring的组件注解)使其被Spring容器管理。 - 使用@Value注入时,属性名必须与配置文件中的键一致(支持松散绑定,例如在配置文件中是my.property,在@Value中可以用${my.property})。 另外,还可以通过@ConfigurationProperties批量注入配置,但这不是本次问题的重点。 生成相关问题: 1. 如何在Spring Boot中同时加载多个自定义配置文件? 2. 如何解决自定义配置文件中的属性被application.properties覆盖的问题? 3. 除了@PropertySource,还有哪些方法可以加载自定义配置文件? 4. 如何在Spring Boot中实现YAML配置文件的加载? </think>在 Spring Boot 中自定义 `@Value` 配置文件路径的方法主要有以下两种实现方式,均通过 `@PropertySource` 注解实现: ### 方法一:加载 classpath 下的自定义配置文件(最常见) ```java @Component @PropertySource("classpath:custom-config.properties") // 指定自定义配置文件路径 public class AppConfig { @Value("${file.storage.path}") // 取自定义配置文件中的属性 private String storagePath; @Value("${api.max.retry}") // 支持取多个属性 private int maxRetry; } ``` **配置示例** (`custom-config.properties`) ```properties # 存储在src/main/resources/custom-config.properties file.storage.path=/data/uploads api.max.retry=5 ``` ### 方法二:加载文件系统绝对路径的配置文件 ```java @Component @PropertySource("file:/etc/app/config/override.properties") // 文件系统路径 public class ExternalConfig { @Value("${db.backup.dir}") private String backupDir; } ``` **注意事项**: 1. **路径前缀规则**: - `classpath:` → 项目资源目录 (`src/main/resources`) - `file:` → 文件系统绝对路径 - 无前缀 → 默认从项目根目录查找 2. **多文件支持**: ```java @PropertySource({ "classpath:base-config.properties", "file:/etc/app/env-config.properties" // 加载多个配置文件 }) ``` 3. **YAML 文件特殊处理**: Spring Boot 默认不支持 `@PropertySource` 加载 YAML,需自定义解析器: ```java @Configuration @PropertySource(value = "classpath:custom.yml", factory = YamlPropertySourceFactory.class) public class YamlConfig { @Value("${security.key}") private String securityKey; } // 自定义YAML解析器 public class YamlPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(resource.getResource()); Properties properties = factory.getObject(); return new PropertiesPropertySource(resource.getResource().getFilename(), properties); } } ``` ### 关键验证步骤 1. **文件存在性**:确认配置文件在指定位置 2. **属性键匹配**:`@Value("${key}")` 的 `key` 需与配置文件一致 3. **依赖注入**: ```java @RestController public class TestController { @Autowired // 必须通过依赖注入使用 private AppConfig appConfig; // 直接注入配置类 } ``` 4. **启动日志检查**:查看是否成功加载配置文件: ``` 2023-XX-XX INFO : Loaded properties from 'classpath:custom-config.properties' ``` ### 常见问题解决 | 问题现象 | 解决方案 | |--------------------------|------------------------------| | 注入值为 `null` | 检查 `@Component` 是否缺失 | | 找不到配置文件 | 确认路径前缀 (`classpath:/` 或 `file:/`) | | YAML 文件属性不到 | 使用自定义 `YamlPropertySourceFactory` | | 属性被覆盖 | 调整配置文件加载顺序[^2] | > **示例**:若 `file:/etc/app/config.properties` 包含 `export.path=/var/exports`,则通过 `@Value("${export.path}")` 可注入值 `/var/exports`[^4] --- ### 相关问题 1. 如何在 Spring Boot 中实现多环境配置切换(dev/test/prod)?[^2] 2. `@Value` 和 `@ConfigurationProperties` 注解应该如何选择?[^3] 3. 如何解决自定义配置属性被默认 `application.properties` 覆盖的问题? 4. Spring Boot 如何支持从云存储(如 S3)加载远程配置文件
评论 5
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值