Java project: Property file from resource directory is not accessible

问题: I am building a jersey-2 webapp. I can't access config.property file from resource. What am I missing? @Bean(name = com.tarkshala.photo.drive.Configuration.CONFIGURATION_...

问题:

I am building a jersey-2 webapp. I can't access config.property file from resource. What am I missing?

@Bean(name = com.tarkshala.photo.drive.Configuration.CONFIGURATION_BEAN_NAME)
public Properties getConfiguration() throws IOException {
    Properties properties = new Properties();
    InputStream input = new FileInputStream("config.properties");
    properties.load(input);
    return properties;
}

Bean initialization fails with following error:

Caused by: java.lang.NullPointerException
    at com.tarkshala.photo.spring.SpringAppConfig.getConfiguration(SpringAppConfig.java:47)
    at com.tarkshala.photo.spring.SpringAppConfig$$EnhancerBySpringCGLIB$$3ecfb6f6.CGLIB$getConfiguration$5(<generated>)
    at com.tarkshala.photo.spring.SpringAppConfig$$EnhancerBySpringCGLIB$$3ecfb6f6$$FastClassBySpringCGLIB$$45328ae1.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)

回答1:

You can try YourCurrentClass.class.getClassLoader().getResourceAsStream("config.properties")


回答2:

The main difference is that when using the getResourceAsStream on a ClassLoader instance, the path is treated as absolute starting from the root of the classpath. reading-file-in-java

public InputStream getResourceFileAsInputStream(String fileName) {
    ClassLoader classloader = SpringAppConfig.class.getClassLoader();
    return classloader.getResourceAsStream(fileName);   
}

public Properties getConfiguration() throws IOException {
    Properties properties = new Properties();
    InputStream input = getResourceFileAsInputStream("config.properties");
    properties.load(input);

    return properties;
} 

java-properties-file-examples

  • 发表于 2020-06-27 21:51
  • 阅读 ( 173 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除