@Value-赋值,@PropertySource读取配置文件
配置
//使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中;加载完外部的配置文件以后使用${}取出配置文件的值 @PropertySource(value = {"classpath:/entity1.properties"}) @Configuration public class MyConfig2 { @Bean public Entity1 entity1(){ return new Entity1(); } }
@Data public class Entity1 { /** * @Value 的三种写法 * 1.基本的数值 * 2.#{} SpEL(Spring 表达式语言) * 3.${} 读取配置文件中数值 */ @Value("张三") private String name; @Value("#{100-30}") private int age; @Value("${entity1.address}") private String address; }
entity1.address=吉林长春
输出
@Test public void Test1(){ AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig2.class); String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); for (String beanDefinitionName : beanDefinitionNames) { System.out.println(beanDefinitionName); } Entity1 entity1 = (Entity1)applicationContext.getBean("entity1"); System.out.println(entity1); }
输出结果
@PropertySource注解值可以写数组填写多个文件
也可以用@PropertySources注解填写多个@PropertySource
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?