M1 使用@PropertySource
+ @Value
-
@PropertySource
如果你需要多个yml文件那么只需要使用@PropertySources
因为value属性支持多个yaml文件,作用:注解告知springboot加载自定义的yml配置文件的位置以及名称,由于springboot默认就会自动加载项目当中的application.yml文件,因此只要你的参数信息直接写在这个文件内,那么就不需要需要显式加载(不需要写这一句注解)
-
@Value
:作用:根据目标属性在yml文件中的全限定名来将对应的值取出装配给对应的属性
-
@Component
:作用:将当前类实例化到spring容器中,相当于xml配置文件中的
<bean id="" class=""/>
package com.xxx.util;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* @author wyrctzy
* @description 用于从配置文件中获取信息,取代IO的方式fileAssociationConfig
* @createOn 2020/10/09
*/
@Data
@PropertySource(value = "classpath:readStandard.yml")
@Component
public class UrlForenConfig {
@Value("${url.resObjectUrl}")
private String resObjectUrl;
@Value("${url.resCfgUrl}")
private String resCfgUrl;
}
需要使用的时候只需要用@Autowired
装配这个类就可以了
M2 使用@ConfigurationProperties
+ @PropertySource
+ @Value
-
PropertySource
和@Value
作用与方法一相同,不再赘述 -
@ConfigurationProperties
作用:之所以加入
@ConfigurationProperties
注解是因为通过设置就可以缩短之后使用@Value
全限定类名长度,使用的是prefix
设置前缀属性的值,现在@Value
只需要指定参数名称,就可以取到值了
package com.xxx.util;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* @author wyrctzy
* @description 用于从配置文件中获取信息,取代IO的方式fileAssociationConfig
* @createOn 2020/10/09
*/
@Data
@ConfigurationProperties(prefix = "url")
@PropertySource(value = "classpath:readStandard.yml")
@Component
public class UrlForenConfig {
@Value("${resObjectUrl}")
private String resObjectUrl;
@Value("${resCfgUrl}")
private String resCfgUrl;
}
tips:@Data
是lombok插件的注解,可以让类看起来更简洁,自动生成Get方法
以上,这是我参照多种方法之后归纳出觉得比较好用的,两种方法,如果后续发现更加使用的方法,会继续补充在这里,欢迎大家指正。