SpringBoot——加载配置文件

本文围绕Spring Boot配置文件展开,介绍了默认读取的配置文件及位置、读取顺序,多环境配置文件的使用方法,如指定不同环境配置文件;还讲解了个性化配置的@Profile注解、自定义配置文件名称和路径的@PropertySource标签,以及加载yml文件的自定义factory实现。
部署运行你感兴趣的模型镜像

springboot默认读取的配置文件名字是:“application.properties”和“application.yml”,默认读取四个位置的文件:根目录下、根目录的config目录下、classpath目录下、classpath目录里的config目录下;

配置文件的读取顺序

  1. 根目录/config/application.properties
  2. 根目录/config/application.yml
  3. 根目录/application.properties
  4. 根目录/application.yml
  5. classpath目录/config/application.properties
  6. classpath目录/config/application.yml
  7. classpath目录/application.properties
  8. classpath目录/application.yml

默认可读取的配置文件全部都会被读取合并,按照顺序读取配置,相同的配置项按第一次读取的值为准,同一个目录下properties文件比yml优先读取,通常会把配置文件放到classpath下,一般是resources里;

多坏境的配置文件

通常可以使用4个配置文件:(yml也同理)

  • application.properties:默认配置文件
  • application-dev.properties:开发环境配置文件
  • application-prod.properties:生产环境配置文件
  • application-test.properties:测试环境配置文件

在application.properties里配置spring.profiles.active以指定使用哪个配置文件,可以配置dev、prod、test分别对应以-dev、-prod、-test结尾的配置文件;(yml配置文件也是同理)

也可以在命令行使用spring.profiles.active指定,例如:java -jar xxxxxx.jar --spring.profiles.active=dev;

个性化配置

对于更特殊的个性化配置可以使用@Profile注解指定;

@Profile标签可以用在@Component或者@Configuration修饰的类上,可以标记类和方法,用来指定配置名字,然后使用spring.profiles.active指定该配置名字就可生效;

就像这样:

/**
 * 2022年10月24日下午3:59:53
 */
package testspringboot.test2;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

/**
 * @author XWF
 *
 */
@Configuration
@Profile("myconfig")
public class MyConfig {
	
	@Bean("Tom")
	@Profile("A")
	public String a() {
		return "tomtom";
	}
	
	@Bean("Tom")
	@Profile("B")
	public String b() {
		return "TOMTOM";
	}
	
	@Bean("Tom")
	public String c() {
		return "ttoomm";
	}
	
}

然后写一个controller类:

/**
 * 2022年10月24日上午10:41:39
 */
package testspringboot.test2;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author XWF
 *
 */
@RestController
@RequestMapping("/test2controller")
public class Test2Controller {

	@Resource(name = "Tom")
	public String t;
	
	@RequestMapping("/test2")
	public String test2() {
		System.out.println(t);
		return "TEST2" + t;
	}
	
}

启动类:

/**
 * 2022年10月24日上午10:41:24
 */
package testspringboot.test2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author XWF
 *
 */
@SpringBootApplication
public class Test2Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SpringApplication.run(Test2Main.class, args);
	}

}

配置文件里配置:

server.port=8888
server.servlet.context-path=/testspringboot

spring.profiles.active=myconfig

只指定myconfig配置,则MyConfig类里c()的bean生效,访问结果是:

修改spring.profiles.active=myconfig,A,则MyConfig类里标记@Profile("A")的bean生效:

修改spring.profiles.active=myconfig,B,则标记@Profile("B")的bean生效:

如果去掉spring.profiles.active配置,则就找不到MyConfig里的配置了,启动失败:

自定义配置文件名称和路径

可以使用@PropertySource标签指定自定义的配置文件名称和路径;(默认能加载到的配置文件也会先被加载)

通常只会用到设置配置文件的名字,并且配置文件的名字可以随便定义,可以叫xxxx.properties、a.txt、b.abc等等,但是内容格式需要跟.properties一致,即kv格式,所以不能直接加载yml格式的配置文件;

@PropertySource默认加载路径是classpath下,可以使用classpath:xxxx/xxxx/xxxx.properties指定目录和文件,如果使用根目录则需要使用file:xxxx/xxxx/xxxx.properties;

可以使用@PropertySource为启动类指定springboot的配置文件,能够做到使用一个main方法启动两个springboot实例,并各自使用不同的配置文件:

@SpringBootApplication
@PropertySource("classpath:a.properties")
@PropertySource(value = "file:a.properties", ignoreResourceNotFound = true)
public class Test2Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SpringApplication.run(Test2Main.class, args);
	}

}

也可以使用@PropertySource配置bean,在使用@Component和@ConfigurationProperties时也可给bean指定特定配置文件:

放在resources下的配置文件tom.abc:

mybean.name=Tom
mybean.age=12

bean类ABC,配置tom.abc文件注入:

/**
 * 2022年10月25日上午10:20:59
 */
package testspringboot.test2;

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

/**
 * @author XWF
 *
 */
@Component
@ConfigurationProperties("mybean")
@PropertySource(value = "classpath:tom.abc")
public class ABC {
	
	public String name;
	
	public 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;
	}

	@Override
	public String toString() {
		return "ABC [name=" + name + ", age=" + age + "]";
	}

}

启动类可以直接获得bean:

/**
 * 2022年10月24日上午10:41:24
 */
package testspringboot.test2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.PropertySource;

/**
 * @author XWF
 *
 */
@SpringBootApplication
@PropertySource("classpath:a.properties")
@PropertySource(value = "file:a.properties", ignoreResourceNotFound = true)
public class Test2Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ConfigurableApplicationContext ctx = SpringApplication.run(Test2Main.class, args);
		System.out.println(ctx.getBean(ABC.class));
	}

}

启动结果:

可以直接获得配置的bean,也可以在代码里使用@Resource或者@Autowired获得;

加载yml文件

如果使用@PropertySource配置yml,则需要自定义一个factory实现:

/**
 * 2022年10月25日下午2:35:35
 */
package testspringboot.test2;

import java.io.IOException;
import java.util.Properties;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

/**
 * @author XWF
 *
 */
public class YmlPropertiesFactory implements PropertySourceFactory {

	@Override
	public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
		YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
		factoryBean.setResources(resource.getResource());
		factoryBean.afterPropertiesSet();
		Properties source = factoryBean.getObject();
		return new PropertiesPropertySource("myyml", source);
	}

}

然后在@PropertySource里配置factory和yml文件:@PropertySource(value = "myapplication.yml", factory = YmlPropertiesFactory.class),就可以加载yml配置文件了;

您可能感兴趣的与本文相关的镜像

Llama Factory

Llama Factory

模型微调
LLama-Factory

LLaMA Factory 是一个简单易用且高效的大型语言模型(Large Language Model)训练与微调平台。通过 LLaMA Factory,可以在无需编写任何代码的前提下,在本地完成上百种预训练模型的微调

### Spring Boot 中 `@ConfigurationProperties` 加载配置文件时赋值失败的原因分析 当遇到 `@ConfigurationProperties` 注入属性为空的情况,通常有以下几个原因: #### 1. 缺少必要的注解组合 如果仅使用 `@ConfigurationProperties` 而未配合其他必要注解,则可能导致属性无法正常注入。为了使自定义配置类生效,除了 `@ConfigurationProperties` 外还需要加上 `@Component` 或者通过 `@EnableConfigurationProperties` 来显式注册这些 Bean。 对于这种情况,在不希望直接标注组件的情况下可以采用如下方式来解决问题[^2]: ```java @SpringBootApplication @EnableConfigurationProperties(UserProperties.class) // 明确指出需要启用哪个配置类 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` #### 2. 配置前缀设置错误 确保在使用 `@ConfigurationProperties` 时指定了正确的 prefix 参数值,并且此前缀与 application.properties 或 application.yml 文件中的键名相匹配。例如: ```java @ConfigurationProperties(prefix = "user") public class UserProperties { private String name; // getter and setter methods... } ``` 对应的配置应为: ```properties user.name=John Doe ``` #### 3. 使用不当的数据类型转换器 有时即使配置正确也可能因为数据类型的自动转换失败而导致某些字段未能成功初始化。此时可以通过实现自定义的 Converter 接口或者利用现有的 SpEL 表达式来进行更复杂的映射逻辑处理。 #### 4. 版本兼容性问题 不同版本之间可能存在 API 变化或行为差异,因此建议查看当前使用的 spring-boot-starter-parent 和相关依赖库的具体版本号是否一致并保持最新状态。 #### 5. 应用上下文刷新顺序影响 由于 Spring 容器启动过程中会经历多个阶段,部分情况下可能会因加载时机不对而造成配置解析异常。可通过调整 bean 初始化顺序等方式尝试修复此类问题。 针对上述提到的方法之一——即确保所有带有 `@ConfigurationProperties` 的类都被适当扫描到并作为 Spring 上下文中的一部分被管理起来这一点尤为重要。这不仅有助于简化代码结构设计同时也提高了系统的可维护性和扩展能力。 另外值得注意的是,虽然 properties 是最基础也是默认支持的一种外部化配置形式[^1],但在实际开发中 YAML 格式的配置文件因其层次化的特性往往更加直观易懂;不过无论选用哪种格式都需遵循相应的语法规则以保证其有效性。 最后提醒一点,若仍然存在读取不到预期配置项的情形,请仔细核对 pom.xml 中关于 spring-boot-dependencies 的引入情况以及是否存在重复声明相同功能模块的现象[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值