springboot在工具类中读取配置文件(ClassPathResource)

1、创建配置文件(application.properties)

spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.user=admin
spring.activemq.password=admin
spring.activemq.in-memory=true
spring.activemq.pool.enabled=false

2、创建工具类(PropertiesUtil.java)

package com.jeff.utils;

import java.io.IOException;
import java.util.Properties;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

public class PropertiesUtil {
     

	private static String user;

	static {
     
		System.out.println("application.properties属性文件读取开始");
		ClassPathResource resource = new ClassPathResource("application.properties");
		try {
     
			Properties properties = PropertiesLoaderUtils.loadProperties(resource);
			user = properties.getProperty("spring.activemq.user");
			System.out.println("user的值:" + user);
		} catch (IOException e) {
     
			System.out.println("application.properties属性文件读取异常" + e);
		}
		System.out.println("application.properties属性文件读取完成");
	}

	public static String getUser() {
     
		System.out.println("获取user的值:" + user);
		return user;
	}

}

3、创建测试类(MyController.java)

package com.jeff.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jeff.utils.PropertiesUtil;

@RestController
public class MyController {
     

	@RequestMapping("myTest")
	public String myTest() {
     
		PropertiesUtil.getUser();
		return "success";
	}

}

4、打开浏览器访问 http://localhost:8080/myTest,控制台输出结果
springboot在工具类中读取配置文件(ClassPathResource)_第1张图片
springboot在工具类中读取配置文件(ClassPathResource)_第2张图片

你可能感兴趣的:(SpringBoot,spring,boot)