15--属性赋值-@Value赋值和@PropertySource加载外部配置文件

使用@Value赋值

  1. 基本数据类型
  2. 可以写:SpringEL表达式#{}
  3. 也可以写${}:取出配置文件【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");

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值