上篇文章介绍了BeanPostProcessor,spring框架生命周期@PostConstruct,@PreDestroy,InitializingBean,disposableBean接口,依赖注入@Autowird都离不开这个接口,@Bean等对象的注入,在bean对象初始化前后还可以调用方法执行事务,对此接口源码也做了深入的了解,在对bean初始化之前,会调用方法先对bean注入属性赋值 ,感兴趣的可以点进去看看:
生命周期BeanPostProcessor(3)---Spring源码从入门到精通(九)
这篇文章主要介绍@Value如何获取值,先给大家贴上项目目录:
首先自定义application.properties放在classpath:/路径下,再自定义配置类,加上@Configuration,在加上@PropertiesSource注解指定配置文件,代码如下:
/** * 人 * * @author keying * @date 2021/6/24 */ public class Person { /** * @Value :1、普通赋值 * 2、#{}计算复制 * 3、&{}加载配置文件,也就是运行环境里面的值 */ @Value("张三") private String name; @Value("${value.name}") private String getProperties; @Value("#{100-50}") private Integer age; @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", getProperties='" + getProperties + '\'' + ", age=" + age + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGetProperties() { return getProperties; } public void setGetProperties(String getProperties) { this.getProperties = getProperties; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Person() { } public Person(String name, String getProperties, Integer age) { this.name = name; this.getProperties = getProperties; this.age = age; } public Person(String name, Integer age) { this.name = name; this.age = age; } }
/** * 使用@PropertySource注解,读取外部配置文件,吧k/v保存到环境变量中 * @author keying */ @Configuration @PropertySource(value = {"classpath:/application.properties"}) public class MyConfigPropertyValues { @Bean("person") public Person person(){ return new Person(); } }
/** * @author keying */ public class IOCTestPropertyValues { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext( MyConfigPropertyValues.class); @Test public void test1() { getBeanNames(applicationContext); Person person = (Person)applicationContext.getBean("person"); System.out.println(person.toString()); System.out.println("加载环境变量中的数据,配置文件的数据也会被@PropertySource注解加载进环境变量中"); ConfigurableEnvironment configurableEnvironment = applicationContext.getEnvironment(); String valueName = configurableEnvironment.getProperty("value.name"); System.out.println("环境变量中的:" + valueName); applicationContext.close(); } private void getBeanNames(AnnotationConfigApplicationContext applicationContext) { String[] names = applicationContext.getBeanDefinitionNames(); for (String name : names) { System.out.println(name); } } }
打印结果如下,从控制台我们可以看到,person组件的内容全部都获取到了,普通的@Value("张三")打印成功,@Value("&{value.name}")配置文件值获取成功,@Value("#{100-50}")spring表达式spEl获取的值获取成功: