spring中读取配置文件的两种方法

方法一:

config.properties

domainUrl=http\://192.168.0.188

ConfigUtil

@Configuration
@ComponentScan
@PropertySource("classpath:config.properties")
public class ConfigUtil {
	
	@Value("${domainUrl}")
	private String domainUrl;

这里就可以获取到domainUrl的值了

但是这里有一个缺陷,就是util类必须被spring管理,不能自己创建对象,

第二种:

public class ConfigUtil {
	/**
	 * 读取配置文件
	 * @param key
	 * @return
	 */
	 public static String getValue(String key){  
	        InputStream is=ConfigUtil.class.getClassLoader().getResourceAsStream("config.properties");  
	        BufferedReader br= new BufferedReader(new InputStreamReader(is));  
	        Properties props = new Properties();  
	        try {  
	            props.load(br);  
	            return (String) props.get(key);
	        } catch (IOException e) {
	            e.printStackTrace();
	        }  
	        return null;
	    }


}

然后在需要的地方调用这个类的getValue(“”)即可

功能一样,使用场景不同,各有个的长处吧

猜你喜欢

转载自blog.csdn.net/qq_38058332/article/details/86615380