Spring 属性赋值
Spring中通过 @Value 给Bean赋值
@Value赋值方式有:
- 基本数值
- 可以写SpEL表达式:#{}
- 可以写${};取出配置文件中的值(在运行环境变量里面的值)
例如:
package com.xiaochao.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
/**
* @program: springDemoCode
* @description:
* @author: 小超
**/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
//基本数值(包括字符串,数字)
@Value("张三")
private String name;
//SpEl表达式:#{}
@Value("#{20-2}")
private int age;
//${}:取出配置文件中的值(在运行环境变量里面的值)
@Value("${person.nickName}")
private String nickName;
}
配置文件person.properties 放置在resource目录下
person.nickName=Tom
配置文件MainConfigOfPropertyValues
package com.xiaochao.config;
import com.xiaochao.pojo.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* @program: springDemoCode
* @description:
* @author: 小超
**/
//使用@PropertySource读取外部配置文件person.properties中的K/V保存到运行的环境变量中
@PropertySource(value = {"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {
@Bean
public Person person(){
return new Person();
}
}
测试:
package com.xiaochao.test;
import com.xiaochao.config.MainConfigOfPropertyValues;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
/**
* @program: springDemoCode
* @description:
* @author: 小超
**/
public class IOCTest_PropertyValue {
AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
@Test
public void test01(){
System.out.println(applicationContext.getBean("person"));
//获取properties文件中的环境
ConfigurableEnvironment environment = applicationContext.getEnvironment();
String property = environment.getProperty("person.nickName");
System.out.println(property);
applicationContext.close();
}
}
测试结果: