使用@Value赋值
- 基本数据类型
- 可以写:SpringEL表达式#{}
- 也可以写${}:取出配置文件【properties】的值(运行在环境变量里面的值)
import org.springframework.beans.factory.annotation.Value;
public class PersonBean {
/**
* 使用@Value赋值
* 1、基本数据类型
* 2、可以写:SpringEL表达式#{}
* 3、也可以写${}:取出配置文件【properties】的值(运行在环境变量里面的值)
*/
@Value("wangwu")
private String name;
@Value("#{2-02}")
private String id;
@Value("${person.nikeName}")
private String nikeName;
public String getNikeName() {
return nikeName;
}
public void setNikeName(String nikeName) {
this.nikeName = nikeName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "PersonBean [name=" + name + ", id=" + id + "]";
}
public PersonBean() {
super();
// TODO Auto-generated constructor stub
}
public PersonBean(String name, String id) {
super();
this.name = name;
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import com.ceshi.bean.PersonBean;
//配置类==配置文件(xml)
@Configuration //告诉Spring这个一个配制类
//使用@PropertySourc读取外部配置文件中的k/v保持到环境变量
@PropertySource(value={"classpath:/person.properties"})
public class BeanConfig2 {
//给容器注册一个Bean,类型class:默认为返回值的类型,标识id:默认为方法名
@Bean("person")
public PersonBean personBean(){
return new PersonBean("lishi","20");
}
}
ApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(BeanConfig2.class);
Environment environment = annotationConfigApplicationContext.getEnvironment();
environment.getProperty("person.nickName");