Spring中如何使用@Value注解与@PropertySource注解加载配置文件呢?
下文笔者讲述Spring中使用@Value注解和@PropertySource注解加载配置文件的方法分享,如下所示
@Value注解简介
Spring框架中对外提供@Value注解
@Value注解的功能:
将外部的值动态注入到Bean中
@Value注解可用在字段、构造器参数和方法参数上
@Value可指定属性取值的表达式,支持通过#{}使用SpringEL来取值
也支持使用${}来将属性来源中(Properties文件、本地环境变量、系统属性等)值注入到Bean的属性中
@Value注解使用场景
1.注入普通字符 2.注入操作系统属性 3.注入表达式运算结果 4.注入其他Bean的属性 5.注入文件内容 6.注入网址内容 7.注入属性文件
@PropertySource注解简介
@PropertySource注解
可加载指定的属性文件
(*.properties)到Spring中Environment
可配合@Value和@ConfigurationProperties使用
@PropertySource注解使用示例
@PropertySource(value = "classpath:com/java265/config/user.properties",encoding = "UTF-8")
public class UserInfo
{
}
例:使用@Value注解和@PropertySource注解加载配置文件
1.创建用户信息属性文件(user.properties)
user.userId=1
user.userName=adeal
user.blogUrl=https://www.java265.com
user.remark=世界上最优秀的Java教程
2.创建用户信息实体类(UserInfo.java)
使用@PropertySource注解加载配置文件信息,然后使用@Value注解注入属性值。
package com.java265.el;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* 用户信息实体类
**/
@Component
@PropertySource(value = "classpath:com/java265.com/el/user.properties",encoding = "UTF-8")
public class UserInfo
{
//用户ID
@Value("${user.userId}")
private int userId;
//用户姓名
@Value("${user.userName}")
private String userName;
//博客地址
@Value("${user.blogUrl}")
private String blogUrl;
//备注
@Value("${user.remark}")
private String remark;
//省略getter与setter方法...
}
//运行测试代码
public static void main(String[] args)
{
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ElConfig.class);
UserInfo userInfo = context.getBean(UserInfo.class);
//打印用户信息
System.out.println("用户编号:" + userInfo.getUserId());
System.out.println("用户姓名:" + userInfo.getUserName());
System.out.println("博客地址:" + userInfo.getBlogUrl());
System.out.println("备注信息:" + userInfo.getRemark());
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


