本篇内容介绍了“Spring中如何实现给Bean属性赋值”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
属性赋值
@Value注解的定义:
测试
1.在添加了Spring依赖的Maven项目中创建
2.在resources目录下创建一个配置文件person.properties
3.创建配置类
4.创建测试类进行测试
5.测试结果:
如何给Bean的属性赋值(注入)
1.通过构造方法设置值。
2.设置注入(通过set方法)
只用Spring注解开发的时候,可以使用@Value搭配@PropertySource注解进行给Bean的属性进行赋值。
@Value
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
/**
* The actual value expression: for example {@code #{systemProperties.myProp}}.
*/
String value();
}
可以看到@Value注解接受的参数只能是字符串,所以使用时参数都需要带上双引号。并且可以在属性,方法,参数等位置上标注。value属性支持以下三种类型:
基本数据类型,包括String,int,boolean等类型。
SpEL,#{}的形式即表示使用SpEL表达式,一般用于获取环境中其他bean的属性,当使用Elivis运算符“表达式1?:表达式2”,比如#{ “obj.property? :default_value” }形式时,这里的obj是取当前容器中的对象,default_value就是前面的值为空时的默认值。
在主配置类中通过@PropertySource注解加载配置文件,然后通过${ property : default_value}的形式取配置文件中的值,其中default_value表示前面的值为空时的默认值。
以下两个实体类Student类和Teacher类
public class Teacher {
public int id;
public String name;
public Teacher() {
// TODO Auto-generated constructor stub
System.out.println("teacher-----创建");
}
public Teacher(int id, String name) {
super();
this.id = id;
this.name = name;
}
//省略getter和setter方法
}
在Student类中使用${}取配置文件的值,#{}取容器中的teacher对象的name属性
public class Student{
@Value("1")
private int id;
@Value("${student.name}")
private String name;
@Value("${student.address:北京}")
private String address;
@Value("#{teacher.name?:'老子'}")
private String teacherName;
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", address=" + address + ", teacherName=" + teacherName + "]";
}
//省略getter和setter方法
}
添加以下值:
student.name=张三
person.address=广州市
使用@PropertySource注解读取外部配置文件person.properties中的key/value保存到运行的环境变量中。
@Configuration
@PropertySource("person.properties")
public class SpringConfig2 {
@Bean
public Student student() {
return new Student();
}
@Bean
public Teacher teacher() {
return new Teacher(2,"老李");
}
}
编写代码获取容器中的id为student的bean和直接获取配置环境的属性值。
public class IoCTest {
@Test
public void test() {
//获取Spring的IOC容器
AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(SpringConfig2.class);
//从容器中获取bean
Student stu = (Student) applicationContext.getBean("student");
System.out.println(stu);
//获取环境变量
ConfigurableEnvironment environment = applicationContext.getEnvironment();
String property = environment.getProperty("person.address");
System.out.println(property);
//关闭容器
applicationContext.close();
}
}
通过property标签(内部是通过调用类的set方法将值注入)
“Spring中如何实现给Bean属性赋值”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。