读取外部jar包配置文件
涉及到框架封装,或其他用途时,可能会要读取外部jar包的配置文件 , 使用方式记录如下。
spring-boot 、 spring 项目同样适用,最主要路径写法是,classpath:/jdbc.properties ,不能用classpath*:/jdbc.properties,外部jar包配置文件在classpath路径下,具体代码如下
Resource resource = resourceLoader.getResource("classpath:/jdbc.properties");
package com.example.mongodemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.IOException;
import java.util.Properties;
@SpringBootApplication
public class MongoDemoApplication {
public static void main(String[] args) throws IOException {
SpringApplication.run(MongoDemoApplication.class, args);
/*重点读取代码*/
ResourcePatternResolver resourceLoader = new PathMatchingResourcePatternResolver();
Resource resource = resourceLoader.getResource("classpath:/jdbc.properties");
Properties inPro = PropertiesLoaderUtils.loadProperties(resource);
System.out.println(inPro.getProperty("jdbc.url"));
}
}