@PropertySource 学习笔记

@PropertySource注解加载指定的属性文件

package com.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication
@EnableEurekaServer
//File协议主要用于访问本地计算机中的文件,就如同在Windows资源管理器中打开文件一样。 
@PropertySource(value = "file:${user.dir}/Config/application.properties")
public class EurekaServerApplication {
	public static void main(String[] args) {
		SpringApplication.run(EurekaServerApplication.class, args);
	}
}
package org.springframework.context.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.io.support.PropertySourceFactory;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(PropertySources.class)
public @interface PropertySource {
    //这个值在Springboot的环境中必须是唯一的,如果不设置,则值为:“class path resource [config/application.properties]“。如果@PropertySource中如果没有设置name值,则name值的生成规则是:根据value值查找到最终封装的Resource子类,然后调用具体的Resource子类实例对象中的getDescription方法,getDescription方法的返回值为最终的name值。
    String name() default "";
    //value值是设置需要加载的属性文件,可以一次性加载多个
    String[] value();
    //如果该文件不存在,则ignoreResourceNotFound为true的时候,程序不会报错,如果ignoreResourceNotFound为false的时候,程序直接报错。实际项目开发中,最好设置ignoreResourceNotFound为false。该参数默认值为false。
    boolean ignoreResourceNotFound() default false;
    //用于指定读取属性文件所使用的编码,我们通常使用的是UTF-8
    String encoding() default "";

    Class factory() default PropertySourceFactory.class;
}

Spring中提供了@Value注解,用于将配置文件中的属性值读取出来并设置到相应的属性中。

例子:

@Component
public class Test{
    @Value("${spring.datasource.username}")
    private  String userName;
}

以上例子读取了配置文件中的spring.datasource.username对应的value。但是使用@Value注解方式有一个不太友好的地方就是,当项目中有大量的属性进行配置的时候,我们需要一个个的在类的字段中增加@Value注解,这样确实很费劲,不过我们可以通过Springboot提供的@ConfigurationProperties注解解决这个问题。

如下例子:

@Component
@ConfigurationProperties(prefix = "spring.datasource") 
public class Test{
    private  String username;
    private  String password;
}

上面的例子,Springboot在处理的时候,会去扫描当前类中的所有字段并进行属性的查找以及组装。比如我们配置的prefix = "spring.datasource",Test类中有username和password两个字段,则username字段需要匹配的属性是prefix+字段=spring.datasource.username,password字段需要匹配的是spring.datasource.password。

如果指定的字段没有找到属性怎么办呢?这个可以进行如下的配置:

@Component
@ConfigurationProperties(prefix = "spring.datasource",ignoreUnknownFields=true,ignoreInvalidFields=true) 
public class Test{
    private  String username;
    private  String password;
}

ignoreUnknownFields:忽略未知的字段。

ignoreInvalidFields:是否忽略验证失败的字段。比如我们在配置文件中配置了一个字符串类型的变量,类中的字段是int类型,那肯定会报错的。如果出现这种情况我们可以容忍,则需要配置该属性值为true。该参数值默认为false。

你可能感兴趣的:(java)