0

I have a utility class to read the environment variables.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public final class PropertyUtil {

    /** The system environment. */
    private static Environment environment;

    public static String getConfigProp(final String key) {
        return environment.getProperty(key);
    }

    @Autowired
    public void setEnvironment(Environment environment) {
        PropertyUtil.environment = environment;
    }
}

And I use it in one bean while initialization. The problem is that it runs file if I deploy the war file on tomcat but if I run the same application as a spring boot application from eclipse, it does not read the environment properties and the return values are therefore null.

Any idea what could be the cause of this problem?

Popeye
  • 1,548
  • 3
  • 25
  • 39
  • You can look at this link .http://stackoverflow.com/questions/19454289/spring-boot-environment-autowired-throws-nullpointerexception – forgeter Mar 30 '17 at 08:59
  • In my case, environment is getting initialized but just that there are no properties inside. – Popeye Mar 30 '17 at 09:27

2 Answers2

0
package com.myspringboot.controller;

import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public  class PropertyUtil  implements EnvironmentAware {

    /** The system environment. */
    public  Environment environment;

    public  String getConfigProp(String key) {
        return environment.getProperty(key);
    }
    @Override
    public void setEnvironment(Environment arg0) {
        environment=arg0;

    }
}
    @Test
    public void testProperty(){
/*      String driver= System.getenv().get("spring.datasource.driverClassName");
        System.out.println(driver);
        System.out.println(PropertyUtil.environment);*/
        String str= propertyUtil.getConfigProp("spring.datasource.driverClassName");
        System.out.println(str);
    }
forgeter
  • 1
  • 2
0
package com.myspringboot.controller;

import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public final  class PropertyUtil  implements EnvironmentAware {

    /** The system environment. */
    public static  Environment environment;

    public static  String getConfigProp(String key) {
        return environment.getProperty(key);
    }
    @Override
    public void setEnvironment(Environment arg0) {
        if(environment==null){
            environment=arg0;
        }

    }
}
forgeter
  • 1
  • 2