Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

193
Vistas
Spring and Constants class from property file

I want to create Constants class with public static final fields, which I get from Properties file. The issue is that ClassLoader always null, and i can't get properties file InputStream.

I'm using Spring Java Configuration and I know about @PropertySource and @Value spring annotations, but I think old-style Constants class more readable in code.

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

vs simple

Constants.ARTICLES_LIMIT //static var version

Here's my code:

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;
    }
}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

After a bit of testing, this is the issue:

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

This prints java.lang.Class which may not have been loaded by the classloader. This is because the class of a SomeClass.class is java.lang.class.

Remove the getClass() and the Classloader won't be null. No need for the clazz variable. This should be all you need to do:

ClassLoader cl = Constants.class.getClassLoader();
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda