spring注解驱动开发-(7) 属性注入

5.1 @Value

可以使用字符串/SpEL/${}表达式

5.2 @PropertySource

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

实例: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;

@Data
public 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@ssword
ds.url=jdbc:mysql://localhost.com://xxx
ds.age1=10
ds.age2=20

output: 可见都正确输出了:

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
propertyReadConfig
tDataSource
=============================
TestDataSource(name=张三, age=23, ageSum=30, passwd=test#P@ssword, url=jdbc:mysql://localhost.com://xxx)

你可能感兴趣的:(spring)