如何或在何处访问我的属性文件

时间:2013-02-25 16:06:21

标签: java spring

我有一个属性文件myprops.properties如下:

Wsdl=someurl
UserName=user
UserPassword=pasword
Application=appName

在我的控制器内部,我正在尝试访问我的服务中的设置值,如下所示

Properties prop = new Properties();
prop.load(new FileInputStream("resources/myprops.properties"));
myService.setWsdl(prop.getProperty("Wsdl"));
myService.setUserName(prop.getProperty("UserName"));
myService.setUserPassword(prop.getProperty("UserPassword"));
myService.setApplication(prop.getProperty("Application"));

我的问题是我只是不知道使用什么路径。它是一个Spring项目,如果这有任何区别。和Idealy我想在我的“src / main / resources”文件夹

中有属性文件

我意识到这可能对某些人来说非常简单,但我已经尝试在这里和Google上搜索解决方案,而我似乎无法找到有帮助的解决方案。我试过在项目周围移动文件,但似乎无法弄明白

我得到的错误是

java.io.FileNotFoundException: resources\drm.properties (The system cannot find the path specified) 

任何建议/解释,甚至是明确解释它的链接都会很棒

5 个答案:

答案 0 :(得分:1)

鉴于src/main/resources在类路径上,您可以这样做:

Resource resource = new ClassPathResource("/myprops.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);

答案 1 :(得分:1)

如果您使用的是spring,则可以设置属性占位符。

 <context:property-placeholder location="classpath:resources/myprops.properties" />

并且在您的bean中,您可以使用@Value注释从属性中注入值

@Autowired
public Foo(@Value("${Wsdl}") String wsdl) {
   ...
}

在我在构造函数中使用的上述情况中,但它可以由Autowired字段/ setter使用。

因此,在您的服务中,您可以拥有类似的内容:

@Service
public class MyService {
     private final String wsdl;
     private final String username;
     private final String password;
     private final String application;

     @Autowired
     public MyService(
         @Value("${Wsdl}") String wsdl,
         @Value("${UserName}") String username,
         @Value("${UserPassword}") String password,
         @Value("${Application}") String application
         ) {
         // set it to each field.
     }
}

答案 2 :(得分:1)

好吧,src / main / resources在classpath上,你只需要这样做。

属性属性= PropertiesLoaderUtils.loadAllProperties(“您的属性文件名”);

答案 3 :(得分:0)

不要使用FileInputStream;使用getResourceAsStream()从servlet上下文中读取它。

答案 4 :(得分:0)

相关问题