Spring boot读取配置文件

1.创建SpringContext类

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContext implements ApplicationContextAware {

	private static ApplicationContext context;
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		context = applicationContext;
	}
	/**
	 * 获取spring容器上下文
	 * @return
	 */
	public static ApplicationContext getApplicationContext() {
	    return context;
	}
	/**
	 * 获取容器中的Bean对象
	 * @param beanid
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static T getBean(String beanid){
		return (T)context.getBean(beanid);
	}
}


2.创建Properties类

import org.springframework.boot.context.properties.ConfigurationProperties;

import lombok.Data;


@ConfigurationProperties(prefix=HessianProperties.PREFIX)
@Data
public class HessianProperties {
	public static final String PREFIX = "hessian";
	/**
	 * ip地址
	 */
	private String ip;
}

3.创建Config类

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;




@Configuration
public class HessianConfiguration {

	@Bean
	@ConfigurationProperties(prefix = "hessian")
	public HessianProperties hessianProperties() {
		return new HessianProperties();
	}

}

4.读取配置文件

private static HessianProperties hessianProperties = SpringContext.getBean("hessianProperties");
private static String ip = hessianProperties.getIp();//"10.106.194.27";
5.配置文件格式

###############IP 配置###########################
hessian:
  ip: 10.106.194.27
###############IP 配置结束#########################





你可能感兴趣的:(java)