gpt4 book ai didi

java - 通过 Spring 将属性文件公开给 Java

转载 作者:行者123 更新时间:2023-12-02 06:27:39 24 4
gpt4 key购买 nike

我正在尝试使用 Spring 来允许我的 Java 类访问属性文件。我已经做了很多谷歌搜索,似乎有几种方法可以做到这一点。我尝试过使用两种不同的方法,但都失败了。

尝试 1
XML

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="location" value=classpath:config.properties />
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>

Java

public class App
{
@Autowired
private static Environment env;

public static void main(String[] args)
{
System.out.println(env.getProperty("DatabaseName"));
}
}

尝试 2
XML

<util:properties id="myProperties" location="classpath:config.properties"/>

Java

public class App
{
@Resource(name="myProperties")
private static Properties myProperties;

public static void main(String[] args)
{
System.out.println(myProperties.getProperty("DatabaseName"));
}
}

在这两种情况下,我在调用“getProperty”方法时都会遇到空指针异常。我是 Spring 新手,我猜我错过了一些简单的东西。除了让这些尝试发挥作用之外,我还想知道使用 Spring 公开属性文件的“最佳”方法是什么。
预先感谢您的帮助。

最佳答案

这是您的另一种方式,这似乎就是您想要的。

==applicationContext.xml==

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd">

<util:properties id="myProperties" location="classpath:config.properties"/>

<bean class="my.pckg.App">
<property name="appProperties" ref="myProperties" />
</bean>
</beans>

==配置.属性==

database.name=blah

==my.pckg.App==

package my.pckg;

import java.util.Properties;

public class App {

private Properties appProperties;

public void setAppProperties(Properties appProperties) {
this.appProperties = appProperties;
}

public String toString() {
return "App (databaseName=" + appProperties.getProperty("database.name") + ")";
}

}

==my.pckg.Main==

package my.pckg;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
App app = appContext.getBean(App.class);
System.out.println(app);
}
}

关于java - 通过 Spring 将属性文件公开给 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20378683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com