@Value 和 @PropertySource 注解
2021/7/8 23:36:52
本文主要是介绍@Value 和 @PropertySource 注解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
@Value 注解赋值
直接给成员变量赋值
Person 类
@Data @NoArgsConstructor @AllArgsConstructor @ToString public class Person { @Value("张三") private String name; @Value("18") private Integer age; }
在 Person 类中,为 name 字段和 age 字段分别做了赋值操作
配置类
@Configuration public class ValueConfig { @Bean public Person person() { return new Person(); } }
在配置类中,并没有调用 person 对象的 setter 方法,只是创建了一个对象
测试代码
@Test public void test10() { ApplicationContext ctx = new AnnotationConfigApplicationContext(ValueConfig.class); Person person = ctx.getBean(Person.class); System.out.println(person); }
直接来看 输出结果
@PropertiesSource 注解配置
直接从 properties 文件中读取
从 properties 文件直接读取配置时,我们需要加载 properties 文件到 IoC 容器中,这时就需要使用 @PropertiesSource 注解告诉 Ioc 容器,properties 文件的位置。在配置类中配置。
properties 文件中的内容
person.name=李四 person.age=30
Person 类
@Data @NoArgsConstructor @AllArgsConstructor @ToString public class Person { @Value("${person.name}") private String name; @Value("${person.age}") private Integer age; }
配置类
@Configuration @PropertySource("classpath:/source.properties") public class ValueConfig { @Bean public Person person() { return new Person(); } }
此时使用 @PropertySource 注解加载 properties 文件
测试代码不变
结果
这篇关于@Value 和 @PropertySource 注解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-09cosmos 开发是什么-icode9专业技术文章分享
- 2024-07-09Cosmos 示例-icode9专业技术文章分享
- 2024-07-09安装Cosmos SDK-icode9专业技术文章分享
- 2024-07-09ubuntu 安装 cosmos-icode9专业技术文章分享
- 2024-07-09cosmos 开发能做到跨链吗-icode9专业技术文章分享
- 2024-07-09app 未公示个人信息的收集范围 的解决办法-icode9专业技术文章分享
- 2024-07-08测试人员在 Scrum 中的角色是什么?
- 2024-07-07Dify + TiDB Vector,快速构建你的AI Agent
- 2024-07-06有没有什么开源的py项目可以对图像进行分类-icode9专业技术文章分享
- 2024-07-05feign默认connecttimeout和readtimeout是多少-icode9专业技术文章分享