0

In my case I am trying to use Environment class to read properties. I tried two options.

Option 1 - I tried to use @Autowired the Enviornment class as shown in the following example.

@Service("idmHelper")
public class IdmHelper {

    @Autowired
    Environment env;

    public IdmHelper() {
       env.getProperty('property-name')
       ...
   }
}

Here it gives a NullPointerException. Becuase env is null.

Option 2 - I tried to use @Autowired inside the constructor as an argument, as shown in the following example.

@Service("idmHelper")
public class IdmHelper {

    public IdmHelper(@Autowired Environment env) {
       env.getProperty('property-name')
       ...
   }
}

Here the env will get an object and I can access the properties. But I am getting the following error;

enter image description here

I am new to spring-boot, can someone explain why I am getting this error. I doubt that it is something to do with initiating the constructor. Please correct me If I am wrong.

This is my full code; Full-code-of-idm-helper-class

1 Answers1

0

Try:

@Service("idmHelper")
public class IdmHelper {

    @Autowired
    Environment env;
    private var prop = null ; 

    @PostConstruct
    public init() {
       prop = env.getProperty('property-name');
   }
}

Other solution :

@Service("idmHelper")
public class IdmHelper {

    @Autowired 
    public IdmHelper(Environment env) {
       ...
   }
}
Zorglube
  • 664
  • 1
  • 7
  • 15
  • This one works fine for me. @Zorglube – Hashan Maduwantha Jul 05 '22 at 11:16
  • If that's work from you fine. However it's definitly possible to put some `autowiering` on a constructor, you ca,n write it like that : ` @Service("idmHelper") public class IdmHelper { @Autowired public IdmHelper(Environment env) { ... } }` – Zorglube Jul 05 '22 at 11:20