实际开发中若需要读取配置文件application.properties中的配置,代码如下。例:读取配置文件中name属性配置值:
代码如下:
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PropertiesLoaderUtils; import java.util.Properties; public class Test { /** * 通过配置文件名读取内容 * @param fileName * @return */ public static Properties readPropertiesFile(String fileName) { try { Resource resource = new ClassPathResource(fileName); Properties props = PropertiesLoaderUtils.loadProperties(resource); return props; } catch (Exception e) { System.out.println("————读取配置文件:" + fileName + "出现异常,读取失败————"); e.printStackTrace(); } return null; } public static void main(String[] args) { Properties properties = readPropertiesFile("application.properties"); System.out.println(properties.getProperty("name")); } }
执行结果: