How to include a properties file in the classpath

0
I'm trying to load a properites file, but when if inside a jar file, in the /userlib or /resources it cannot be found. I'm trying to load a Spring Context file from a jar file. This is what I have in a Java Action that works in non-Mendix projects I use. private static ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "classpath:SpringContext.xml" }); Regardless of where I put the file, it cannot be found. The only way I have gotten it to load is from the file system, but that is not acceptable.
asked
2 answers
1

You should be able to do something like the following:

Add the prop.properties file to your Mendix project's resources directory:

    Properties properties = new Properties();
    try {
      properties.load(new FileInputStream(Core.getConfiguration().getResourcesPath() + File.separator + "prop.properties"));
    } catch (IOException e) {
        // handle errors
    }

Or, if the prop.properties file is accessible from within the class (nameOfClass should be replaced) that contains the properties file in the jar package:

    Properties properties = new Properties();
    try {
        properties.load(nameOfClass.class.getResourceAsStream(File.separator + "prop.properties"));
    } catch (IOException e) {
        // handle errors
    }
answered
0

My issue related to using the default classloader. This could not see files in the resources or userlib folder. Changing the way I initiated Spring I could finally load properties files from the userlib folder.

The problem was how I was loading Spring. Using ClassPathXmlApplicationContext does not work.

You must specify an alternative classloader that can see the libraries in /userlib.

I followed the advice from this answer using a class that was in the same library where my Spring configuration was defined.

final ClassLoader clientClassLoader = SomeSpringBean.class.getClassLoader();

ApplicationContext context = new ClassPathXmlApplicationContext("classpath:SpringContext.xml") {

    @Override
    protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader) {
        super.initBeanDefinitionReader(reader);
        reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
        reader.setBeanClassLoader(clientClassLoader);
        setClassLoader(clientClassLoader);
    }
};
answered