我是春天和春天的新手。我尝试构建一个应用程序并从属性文件中读取一些键值对。
我创建了一个myconfig.properties文件并将其保存到src / main / resources / META-INF / spring /。 该文件的内容是:
## My Configuration settings
myconfig.url=https://1.2.3.4/api.php
myconfig.username=user1
myconfig.password=password1
现在我在同一目录
中的appilcationContext.xml中添加了一个bean配置 <bean id="MyConfig" class="com.test.client.MyClient">
<property name="url" value="${myconfig.url}" />
<property name="username" value="${myconfig.username}" />
<property name="password" value="${myconfig.password}" />
</bean>
在我的类文件中,我尝试访问这些值,但是我收到了File not found错误
package com.test.client;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class MyClient {
private String url;
private String username;
private String password;
public static String login()
{
// Construct the spring application context
AbstractApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
MyClient config = (MyClient) context.getBean("MyConfig");
// Register hook to shutdown Spring gracefully
// See http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-factory-shutdown
context.registerShutdownHook();
String token = null;
final String url = config.getUrl();
final String username = config.getUsername();
final String password = config.getPassword();
....
感谢您的帮助!
答案 0 :(得分:1)
尝试
AbstractApplicationContext context = new ClassPathXmlApplicationContext("classpath*:META-INF/spring/applicationContext.xml");
但最佳做法是实现接口ApplicationContextAware
。
斯特凡诺