面試機試:做一個根據路徑動態讀取propertis文件的Demo
可以下通過兩種方式實現:
1.使用java.util.Properties通過反射將配置文件讀取到實體類中
2.通過SpringBoot的ConfigurationProperties自動讀取文件,然後在pom文件中配置profiles,通過profiles切換Spring配置文件與properties文件
第一種方法比較古老了
工具類代碼
public static <T> T readPropertiesToObject(Class<T> clazz,String configPath,String prefix) throws Exception {
Properties prop=readProperties(configPath);
Field[] fields = clazz.getDeclaredFields();
T result=clazz.newInstance();
for(Field field:fields){
String fieldName=field.getName();
String propName= StringUtils.isEmpty(prefix)?fieldName:prefix+"."+fieldName;
if (prop.get(propName)!=null){
field.setAccessible(true);
field.set(result,prop.get(propName));
}
}
return result;
}
public static Properties readProperties(String configPath)throws Exception{
FileInputStream fis=null;
try {
File file=new File(PropertiesUtil.class.getClassLoader().getResource(configPath).getFile());
if (!file.exists()){
log.error("file isn't exists. ["+file.getAbsolutePath()+"]");
throw new FileNotFoundException();
}
fis=new FileInputStream(file);
Properties prop=new Properties();
prop.load(fis);
return prop;
} catch (Exception e) {
e.printStackTrace();
log.error("read file exception :"+e);
throw e;
}finally {
if (fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
log.error("FileInputStream close exception :"+e);
}
}
}
}
spring讀取的方式:
實體類上增加註解@PropertySource(value=“classpath:authinfo-${spring.profiles.active}.properties”,ignoreResourceNotFound = true,encoding = “utf-8”)
ignoreResourceNotFound 標書如果找不到配置文件spring不會報錯,默認爲false
@ConfigurationProperties(prefix = “auth”)
配置文件屬性的前綴
實體類(配置文件裝載類)
@Component
@Data
@PropertySource(value="classpath:authinfo-${spring.profiles.active}.properties",ignoreResourceNotFound = true,encoding = "utf-8")
@ConfigurationProperties(prefix = "auth")
public class Authinfo {
private String orgName;
private String userName;
private String password;
private String userId;
private String serverPath;
public String toString(){
return orgName+" --- "
+userName+" --- "
+password+" --- "
+userId+" --- "
+serverPath;
}
}
pom文件中添加profiles配置
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
<port>8080</port>
<cxt>/dev</cxt>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>prd</id>
<properties>
<env>prd</env>
<port>8088</port>
<cxt>/prd</cxt>
</properties>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<env>test</env>
<port>8082</port>
<cxt>/test</cxt>
</properties>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
</profile>
</profiles>
spring配置文件
使用佔位符@@讀取pom文件中activeByDefault爲true的profile中的properties
spring.profiles.active設置spring讀取的配置文件,通過佔位符方便切換
spring:
profiles:
active: @env@
server:
port: @port@
servlet:
context-path: @cxt@
Spring配置文件用到@@獲取Pom中的變量要須繼承spring-boot-starter-parent
或者添加resource的flitering
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>*.*</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
或
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>
</parent>
springboot啓動類上增加註解@EnableConfigurationProperties,設置配置文件對應實體類
@SpringBootApplication
@EnableConfigurationProperties(value = {Authinfo.class})
public class PropertiesLoaderApplication {
public static void main(String[] args) {
SpringApplication.run(PropertiesLoaderApplication.class, args);
}
//PropertyPlaceholderConfigurer是個bean工廠後置處理器的實現,也就是 BeanFactoryPostProcessor接口的一個實現。
//在Spring中,使用PropertyPlaceholderConfigurer可以在XML配置文件中加入外部屬性文件,當然也可以指定外部文件的編碼。PropertyPlaceholderConfigurer可以將上下文(配置文 件)中的屬性值放在另一個單獨的標準java Properties文件中去。在XML文件中用${key}替換指定的properties文件中的值。這樣的話,只需要對properties文件進 行修改,而不用對xml配置文件進行修改
/*@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
PropertySourcesPlaceholderConfigurer c = new PropertySourcesPlaceholderConfigurer();
c.setIgnoreUnresolvablePlaceholders(true);
return c;
}*/
}
properties配置文件
auth.userName=dev
auth.password=123456
配置文件結構
注入
@Autowired
private Authinfo authinfo;
private static String HTTP_URL ;
@Value(value = "${message.service.url:default}")
public void setURL(String path){
HTTP_URL=path;
System.out.println(path);
}
通過修改Pom文件切換配置文件切換環境