java - 属性文件中的 Spring 和常量类

标签 java spring

我想创建带有公共(public)静态最终字段的常量类,我从属性文件中获取这些字段。 问题是 ClassLoader 始终为 null,我无法获取属性文件 InputStream。

我正在使用 Spring Java Configuration 并且我知道 @PropertySource 和 @Value spring 注释,但我认为旧式常量类在代码中更具可读性。

@Autowired
Constants constants;//in every class that needs constant
//...
constants.getArticleLimit()

与简单

Constants.ARTICLES_LIMIT //static var version

这是我的代码:

package org.simpletest.utils

import org.apache.log4j.Logger;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class Constants {

    private static final Logger LOG = Logger.getLogger(Constants.class);

    public static final int ARTICLES_LIMIT;

    public static final String PROPERTIES_LOCATION = "constants.properties";

    static {
        Properties p = new Properties();

        //default values
        int articlesLimit = 10;

        Class<?> clazz = Constants.class.getClass(); 

        ClassLoader cl = clazz.getClassLoader();

        //try to load from properties file
        try(final InputStream is = cl.getResourceAsStream(PROPERTIES_LOCATION)){

            p.load(is);

            articlesLimit= Integer.parseInt(p.getProperty("articleslimit"));

        } catch (IOException e) {
            LOG.debug(String.format("Unable to load {0} properties file. Getting constants by default values.",PROPERTIES_LOCATION),e);
        }

        ARTICLES_LIMIT = articlesLimit;
    }
}

最佳答案

经过一些测试,这是问题所在:

System.out.println(Constants.class.getClass());

这会打印 java.lang.Class ,它可能还没有被类加载器加载。这是因为 SomeClass.class 的类是 java.lang.class

删除 getClass() 并且 Classloader 不会为 null。不需要 clazz 变量。这应该是您需要做的所有事情:

ClassLoader cl = Constants.class.getClassLoader();

关于java - 属性文件中的 Spring 和常量类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42768629/

相关文章:

java - apache Camel 混合组件

java - Spring框架和Spring Boot的区别?

java - Cassandra 0.7.4 - 使用 Java,如何为请求关联键空间?

java - 为什么称为 "anonymous"内部类?

java - 如何在 Spring Boot 1.5.1 Hibernate 中防止隐式缓存

java - Spring Boot 2.1.3.RELEASE : Not able to read environment properties from application. 属性

java - HTTP 状态 405 - 不支持请求方法 'PUT'

java - 安卓。如何从另一个文件访问一个类到MainActivity

java - 具有嵌套对象的对象的两个实例与动态比较(选项/规则/参数)

java - 如何在 Jython 中创建符号链接(symbolic link)