【问题标题】:Reading file.properties value in java code在 java 代码中读取 file.properties 值
【发布时间】:2017-07-20 05:44:36
【问题描述】:

我有一个属性文件名为 documentum,内容如下

#test
dfs.repositoryName = CUDO
dfs.contextRoot = http://13.209.9.28:9080/services
dfs.username = 1234
dfs.password = fx8888
dfs.moduleName = core

我已经在 beans.xml 中配置了这个文件

<bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="ignoreUnresolvablePlaceholders" value="false" />
        <property name="locations">
            <list>
                <value>file:${app.home}/documentum.properties</value>
            </list>
        </property>
    </bean>

现在我想做这样的事情,但我不知道如何在我的 java 代码中实现这一点。

String repository = ${dfs.repositoryName};

如果我在同一个类中使用 @value 注释,那么它工作正常,但如果我像这样用作单独的类

package au.com.fxa.sfdc.custdocs.util;

import org.springframework.beans.factory.annotation.Value;

public class DocumentumConfigUtil {


    @Value("${dfs.repositoryName}")
    private String repositoryName;

    @Value("${dfs.contextRoot}")
    private String contextRoot;

    @Value("${dfs.username}")
    private String username;

    @Value("${dfs.password}")
    private String password;

    @Value("${dfs.module}")
    private String module;

    public String getRepositoryName() {
        return repositoryName;
    }

    public String getContextRoot() {
        return contextRoot;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getModule() {
        return module;
    }

}

然后创建这个类的一个对象并尝试通过getter方法访问它给我空值。

【问题讨论】:

  • 我可以看到你在谈论 spring 而不是 web 服务。如果我是对的,请查找 @Value 注释。
  • 是的,很抱歉使用 apache cxf 和 spring 框架创建 Web 服务。
  • @Value like @Autowired 仅适用于 Spring 托管 bean。如果你自己创建一个实例,spring 将对该 bean 一无所知,因此忽略 @Value

标签: java spring properties


【解决方案1】:

使用@Value 注释。

定义一个类属性,如

@Value("${dfs.repositoryName}")
String repository

【讨论】:

  • 谢谢詹斯。如果我在同一个类中定义它是有效的。但是如果我在另一个类中定义属性并通过 getter 尝试访问这些属性,它会给我 null。
  • @Adeel 编辑您的问题,添加标题更新并在那里分享,或者您有 github 存储库吗?
  • @Adeel 这个类不是spring bean,所以属性的注入不起作用。在类中添加@Configuration注解
  • 我添加了@configuration并得到异常说org.springframework.beans.factory.BeanCreationException:无法自动装配字段:(
  • @Adeel 哪个字段?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-25
  • 2018-11-18
  • 1970-01-01
  • 1970-01-01
  • 2011-10-28
相关资源
最近更新 更多