5.1 @Value

能够应用字符串/SpEL/${}表达式

5.2 @PropertySource

指定配置文件, 相当于之前的

<context:property-placeholder location="classpath:jdbc.properties"/>

实例:bean

  • @Value("张三"): 常量字符串;
  • @Value("#{20+3}"): spEL表达式;
  • @Value("#{${ds.age1}+${ds.age2}}"): spEL表达式;
  • @Value("${ds.passwd}"): 读取配置文件;
package com.niewj.bean;import lombok.Data;import org.springframework.beans.factory.annotation.Value;@Datapublic class TestDataSource {    @Value("张三")    private String name;    @Value("#{20+3}")    private int age;        // 这种居然都能够!!!    @Value("#{${ds.age1}+${ds.age2}}")    private int ageSum;    @Value("${ds.passwd}")    private String passwd;    @Value("${ds.url}")    private String url;    public TestDataSource() {    }    public TestDataSource(String name, String passwd, String url) {        System.out.println("User-初始化!");        this.name = name;        this.passwd = passwd;        this.url = url;    }}

配置类:

留神 @PropertySource 是在配置类 PropertyReadConfig 这里标注的!

package com.niewj.config;import com.niewj.bean.TestDataSource;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;@Configuration@PropertySource(value = "classpath:/jdbc.properties")public class PropertyReadConfig {    @Bean    public TestDataSource tDataSource(){        return new TestDataSource();    }}

测试用例:

package com.niewj;import com.niewj.bean.TestDataSource;import com.niewj.config.PropertyReadConfig;import org.junit.Test;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import java.util.stream.Stream;/** * spring属性注入/读取 */public class PropertyFillTest {    @Test    public void testPropety() {        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(PropertyReadConfig.class);        // 打印spring容器中的 BeanDefinition        Stream.of(ctx.getBeanDefinitionNames()).forEach(e-> System.out.println(e));        System.out.println("=============================");        TestDataSource ds = ctx.getBean(TestDataSource.class);        System.out.println(ds);        ctx.close();    }}

jdbc.properties:

ds.passwd=test#P@sswordds.url=jdbc:mysql://localhost.com://xxxds.age1=10ds.age2=20

output: 可见都正确输入了:

org.springframework.context.annotation.internalConfigurationAnnotationProcessororg.springframework.context.annotation.internalAutowiredAnnotationProcessororg.springframework.context.annotation.internalCommonAnnotationProcessororg.springframework.context.event.internalEventListenerProcessororg.springframework.context.event.internalEventListenerFactorypropertyReadConfigtDataSource=============================TestDataSource(name=张三, age=23, ageSum=30, passwd=test#P@ssword, url=jdbc:mysql://localhost.com://xxx)