关于注入数据说明
1.不通过配置文件注入数据
通过@Value将外部的值动态注入到Bean中,使用的情况有:
- 注入普通字符串
- 注入操作系统属性
- 注入表达式结果
- 注入其他Bean属性:注入Student对象的属性name
- 注入文件资源
- 注入URL资源
辅助代码
package com.hannpang.model;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Component(value = "st")//对student进行实例化操作public class Student { @Value("悟空") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; }}测试@Value的代码
package com.hannpang.model;import org.springframework.beans.factory.annotation.Value;import org.springframework.core.io.Resource;import org.springframework.stereotype.Component;@Componentpublic class SimpleObject { @Value("注入普通字符串") private String normal; //关于属性的KEY可以查看System类说明 @Value("#{systemProperties['java.version']}")//-->使用了SpEL表达式 private String systemPropertiesName; // 注入操作系统属性 @Value("#{T(java.lang.Math).random()*80}")//获取随机数 private double randomNumber; //注入表达式结果 @Value("#{1+2}") private double sum; //注入表达式结果 1+2的求和 @Value("classpath:os.yaml") private Resource resourceFile; // 注入文件资源 @Value("http://.hanpang.service")public class SpringConfig { // 通过该注解来表明是一个Bean对象,相当于xml中的<bean> //bean的id值默认是方法名userDao }附录
随机数
${random.value}、${random.int}、${random.long}${random.int(10)}、${random.int[1024,65536]}以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。