在配置文件中可以通过property 标签对Bean进行注值:
<context:component-scan base-package="com.xinyi"></context:component-scan>
<bean id="Person" class="com.xinyi.bean.Person" init-method="" destroy-method="">
<property name="name" value="新一"></property>
<property name="age" value="18"></property>
</bean>
在spring的注解开发中可以使用@value注解对Bean的属性进行赋值,代码如下:
新建一个person实体类,
package com.xinyi.bean;
import org.springframework.beans.factory.annotation.Value;
public class Person {
private String name;
private Integer age;
private String sname;
public String getName() {
return name;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", sname=" + sname + "]";
}
public Person(String name, Integer age, String sname) {
super();
this.name = name;
this.age = age;
this.sname = sname;
}
public Person() {
}
}
在配置类中讲Bean注入IOC容器:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.xinyi.bean.Person;
@Configuration
public class MyConfig2 {
@Bean
public Person person() {
return new Person();
}
}
测试代码输出Bean
@Test
public void test6() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig2.class);
Person person = (Person) applicationContext.getBean("person");
System.out.println(person);
}
由于没对Bean的name、age和sname属性进行赋值,所以输出的结果都为null:
在配置类文件中也可以直接进行属性赋值,不过这种调用有参构造函数的方式比较僵硬。
@Bean
public Person person() {
return new Person("亚索",23,"孤儿玩家");
}
通过@Value将外部的值动态注入到Bean中,并且@value注解可以配合@PropertySource注解将外部配置文件的值注入Bean的属性,代码如下
package com.xinyi.bean;
import org.springframework.beans.factory.annotation.Value;
public class Person {
//@value基本类型赋值
@Value("亚索")
private String name;
//@value:SpEL表达式赋值,下面结果为24
@Value("#{23+1}")
private Integer age;
//@value:获取properties配置文件中的值需要搭配@PropertySource注解(在配置类上)
@Value("${person.sname}")
private String sname;
public String getName() {
return name;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", sname=" + sname + "]";
}
public Person(String name, Integer age, String sname) {
super();
this.name = name;
this.age = age;
this.sname = sname;
}
public Person() {
}
}
person.properties配置文件
获取person.properties配置文件中的sname的值需要在配置类上加上@PropertySource注解,
@PropertySource(value={"classpath:/person.properties"})
结果如下:
以上就是如何在spring开发中给Bean的属性注值的方式。