SpringBoot读取配置文件并注入到静态变量中(已废弃)

1 读取配置文件到常量中

大家熟知的方式是将配置文件注入到一个bean中去访问,但是这种方式每次使用这个bean都要写一个注入@Autowired去引用这个bean不是很方便,如果将配置文件注入到一个配置常量用,那么每次访问用Constant.NAME就可以了,这样是不是方便了很多

package com.pibigstar.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * 常量
 * @author pibigstar
 *
 */
@Configuration
public class Constant {
	//此数据是读取的配置文件
	public static String DEFAULT_FILE_UPLOAD_PATH;
	//注入
	 @Autowired(required = false)
	 public void setUploadPath(@Value("${parsevip.file.path}")String DEFAULT_FILE_UPLOAD_PATH) {
		 Constant.DEFAULT_FILE_UPLOAD_PATH = DEFAULT_FILE_UPLOAD_PATH;
	 }
	
}

配置文件application.yml中:

parsevip:
  file:
    path: D://upload/

使用

//任意处
String filePath = Constant.DEFAULT_FILE_UPLOAD_PATH;

2 读取自定义的配置文件

那我们可不可以读取自定义的配置文件呢,答案是肯定的,看代码

package com.pibigstar.common.config;

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

/**
 * 读取配置文件的自定义常量
 * @author pibigstar
 *
 */
@Configuration
@PropertySource("classpath:myconfig.properties")
@ConfigurationProperties(prefix="parsevip")
public class MyConfiguration {
	
	private String filePath;

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
	
}

使用:

	@Autowired
	private MyConfiguration myConfig;

myconfig.properties (将此文件放到src/main/resources目录下)

parsevip.filePath=D://temp

有一点要注意:用此方法必须为*.properties 文件,不能是yml文件,不知道yml文件应该怎么读取,有知道的麻烦留言告诉我一声,不胜感激。。。。

yml文件操作

用两个类去实现,一个类实现配置自动注入,另一个使用常量引用它

@Component("DefaultProperties")
@ConfigurationProperties(prefix = MessageProperties.MESSAGE_PREFIX)
public class DefaultProperties {
	public static final String MESSAGE_PREFIX = "app.default";
	private String name;
	private String version;
	// setter,getter方法
}

引用它

public class Constants {
    private static final DefaultProperties properties = BeanFactory.getBean("DefaultProperties");
    public static final String NAME = properties.getName();
    public static final String VERSION = properties.getVersion();
}

yml文件

app:
  default:
   name: test
   version: 1.0

使用

Constants.NAME
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值