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

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

Topic source
@Component
public class AppService {

	private String name;
	private String version;

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

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

	private String logo;

	@PostConstruct
	public void init() throws IOException {
		try (var reader = new BufferedReader(
				new InputStreamReader(logoResource.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.name: " + name);
		System.out.println("app.version: " + version);
	}
}

zjsong2011

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

@Value("classpath:/logo.txt"),我使用classpath的路径不是eclipse项目下默认的resources路径,

后来使用了@Value("file:盘符+路径/resources/logo.txt"),才正确,我想知道,在eclipse中classpath路径是什么路径?

廖雪峰

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

Maven学得不扎实啊,回一下锅

zjsong2011

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

好吧

zjsong2011

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

只看“Java教程”的Maven基础行吗?网上关于Maven的资料太多了,很多都是以前的,不知现在还能用

zjsong2011

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

Spring怎么知道这样写就是在resources目录下,

classpath:/logo.txt

这个classpath路径难道是:F:/eclipse/workspace/web-servlet-hello/src/main/resources/

Properties props = new Properties();

这段代码何意?自己写了个类来解析properties文件,然后写成construct方法吗?

知道了,引用了import java.util.Properties这个工具类

你这是不是要加 ./?


  • 1

Reply