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解析

原创文章 83 获赞 155 访问量 36万+

猜你喜欢

转载自blog.csdn.net/qq_28410283/article/details/90742940