Spring注解@Value用法

2 篇文章 0 订阅

1.注入普通字符串

@Value("My name is Shelly")
private String name;

2.注入操作系统属性

 @Value("#{systemProperties['os.name']}")
 private String osName;

3.注入表达式结果

@Value("#{T(java.lang.Math).random() * 100.0}")
private String randomNumber;

4.注入其他Bean属性

@Value("#{testService.another}")
private String fromAnother;

5.注入文件资源

@Value("classpath:com/moam/config/text.txt")
private String testFile;

6.注入网址资源

@Value("http:www.baidu.com")
private String testUrl;

7.注入配置文件

@Value("${index.name}")
 private String indexName;

注入配置文件需使用@PropertySource指定properties文件位置,且使用的是$而不是#,具体如何配置和使用可参考https://blog.csdn.net/weixin_45609759/article/details/117226276

然而当我们的配置有许多个时,我们就需要用@Value注入很多次,这样显得格外麻烦。
SpringBoot提供了基于类型安全的配置方式,@ConfigurationProperties将properties属性和一个Bean及其属性关联。

①配置application.properties

user.name=xxx
user.age=22

②Bean代码

@Component
// 指定配置文件位置
@PropertySource("classpath:application.properties")
// prefix指定properties的配置的前缀
@ConfigurationProperties(prefix = "user")
public class TestBean {
    private String name;
    private Long age;
    
	public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getAge() {
        return age;
    }

    public void setAge(Long age) {
        this.age = age;
    }
    

检验代码:

@RestController
public class TestApplication{
	@Autowired
	private TestBean testBean;
	
	@RequestMapping("/")
	public String index(){
		return "user name is " + testBean.getName() + "user age is " + testBean.getAge();
	}
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值