存在目的:
- 使用@Value和@ConfigurationProperties可以从全局配置文件application.properties或者application.yml中取值,然后为需要的属性赋值。
- 但是当应用比较大的时候,如果所有内容都在一个配置文件中,会显得比较臃肿,同时也不太好理解和维护,此时可以将一个文件拆分成多个,使用@PropertySource注解可以加载指定的配置文件。
@PropertySource源码
@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Repeatable(PropertySources.class)public @interface PropertySource {//属性源的名称String name() default "";//属性文件的存放路径String[] value();//如果指定的属性源不存在,是否忽略这个错误boolean ignoreResourceNotFound() default false;//属性源的编码格式String encoding() default "";//属性源工厂Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;}
使用示例:
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/areajdbc.username=rootjdbc.password=MGY2207242001
@Configuration//<context:property-placeholder location="classpath:config/jdbc.properties"/>@PropertySource(value = "classpath:config/jdbc.properties", encoding = "utf-8")public class DataSourceConfiguration {@Value("${jdbc.driver}")private String drive;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;}
@Configuration//<context:property-placeholder location="classpath:config/jdbc.properties"/>@PropertySource(value = {"config/jdbc.properties"}, encoding = "utf-8")@ConfigurationProperties(prefix = "jdbc")public class DataSourceConfiguration {private String drive;private String url;private String username;private String password;}
