Discuss / Java / 练习:使用Spring的Resource注入app.properties文件,然后读取该配置文件

练习:使用Spring的Resource注入app.properties文件,然后读取该配置文件

Topic source

jasmine

#1 Created at ... [Delete] [Delete and Lock User]

AppService.java

package com.itranswarp.learnjava;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

@Component
public class AppService {

	@Value("1")
	private String version;

	@Value("classpath:/logo.txt")
	private Resource resource;

	@Value("classpath:/app.properties")
	private Resource properties;

	private String logo;
	private String name;

	@PostConstruct
	public void init() throws IOException {
		try (var reader = new BufferedReader(
				new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
			this.logo = reader.lines().collect(Collectors.joining("\n"));
		}

		try (var input = new InputStreamReader(properties.getInputStream(), StandardCharsets.UTF_8)) {
			Properties props = new Properties();
			props.load(input);
			this.name = props.getProperty("app.name", "Cannot fetch the property [app.name]");
			this.version = props.getProperty("app.version", "Cannot fetch the property [app.version]");
		}
	}

	public void printLogo() {
		System.out.println(logo);
		System.out.println("app.version: " + version);
		System.out.println("app.name:"+name);
	}

}

运行结果:

  _____            _
 / ____|          (_)               /\
| (___  _ __  _ __ _ _ __   __ _   /  \   _ __  _ __ 
 \___ \| '_ \| '__| | '_ \ / _` | / /\ \ | '_ \| '_ \
 ____) | |_) | |  | | | | | (_| |/ ____ \| |_) | |_) |
|_____/| .__/|_|  |_|_| |_|\__, /_/    \_\ .__/| .__/
       | |                  __/ |        | |   | |
       |_|                 |___/         |_|   |_|
app.version: 1.0-SNAPSHOT
app.name:SpringAppDemo

  • 1

Reply