天天看點

spring 注解@PropertySource 引入檔案,@Value讀取檔案内容,EmbeddedValueResolverAware讀取檔案内容

@Value注解:

1、基本數值;

2、可以寫SpEL; #{};

3、可以寫${};取出配置檔案【properties】中的值(在運作環境變量裡面的值)

@PropertySource 導入一個外部的配置檔案,相當于xml中如下配置

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

 我們先看下@PropertySource注解的定義

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(PropertySources.class)
public @interface PropertySource {

	/**指定檔案的路徑*/
	String name() default "";

	/**指定檔案的路徑,多個檔案*/
	String[] value();
	/**
	   預設false:value或者name屬性,引用的檔案,必須有,否則會報錯
	   true:引用的檔案不存在,不會報錯
	 * Indicate if failure to find the a {@link #value() property resource} should be
	 * ignored.
	 * <p>{@code true} is appropriate if the properties file is completely optional.
	 * Default is {@code false}.
	 * @since 4.0
	 */
	boolean ignoreResourceNotFound() default false;

	/**
		預設為UTF-8編碼
	 * A specific character encoding for the given resources, e.g. "UTF-8".
	 * @since 4.3
	 */
	String encoding() default "";

	/**
	   這個玩意,看樣子,應該是指定一個預設的配置檔案解析器,也可以自定義,具體參看DefaultPropertySourceFactory和ResourcePropertySource
	   沒有特殊的需求,誰沒事去寫一個解析器
	 * Specify a custom {@link PropertySourceFactory}, if any.
	 * <p>By default, a default factory for standard resource files will be used.
	 * @since 4.3
	 * @see org.springframework.core.io.support.DefaultPropertySourceFactory
	 * @see org.springframework.core.io.support.ResourcePropertySource
	 */
	Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;

}
           

使用方式:

1.定義一個jdbc.properties檔案 

db.user=root
db.password=123456
db.driverClass=com.mysql.jdbc.Driver
           

定義配置類,引入jdbc檔案

@PropertySource("classpath:/jdbc.properties")
@Configuration
public class MainConfigOfProfile2 implements EmbeddedValueResolverAware {

    @Value("${db.user}")
    private String user;

    @Value("張三")
    private String name;
    @Value("#{20-2}")
    private Integer age;

    private StringValueResolver valueResolver;

    private String driverClass;

    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        this.valueResolver = resolver;
        driverClass = valueResolver.resolveStringValue("${db.driverClass}");
    }
}
           

一.在使用上,我們可以使用@Value指派

@Value注解:

1、基本數值;

2、可以寫SpEL; #{};

3、可以寫${};取出配置檔案【properties】中的值(在運作環境變量裡面的值)

二:可以實作EmbeddedValueResolverAware接口,重寫 public void setEmbeddedValueResolver(StringValueResolver resolver) 方法,使用resolver解析

繼續閱讀