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

34次阅读

共计 2456 个字符,预计需要花费 7 分钟才能阅读完成。

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;

@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)

正文完
 0