0

I have a entry on application.properties like this.

stackoverflow.questiontitle=I cant see this from environment

But in my code im unable to see it.

enter image description here

As you cann see the @Value is working but this time i need it from Environment or ApplicationContext how can i do that? thanks

Yep i mean the @Value i can see the property but i need it from Environment on other class yep is failing on runtime

Is running prod profile

chiperortiz
  • 4,751
  • 9
  • 45
  • 79
  • Which environment is you application running? Usually you have environments like local, staging, prod. In which file is your properties and which environment are you running may give you the answer – Jorge Campos Feb 09 '23 at 18:08
  • Just to be clear is not working at runtime or is it something else? – Jorge Campos Feb 09 '23 at 18:09
  • You can't get a property from the `Environment` that is for OS environment variables. What you can do, is to define your property to come from the OS `Environment` like `stackoverflow.questiontitle=${OS_ENV_QUESTION_TITLE}` and make sure it exists on that environment. – Jorge Campos Feb 09 '23 at 18:42
  • Thanks Jorge all i want to do is get programmatically a entry from file application.properties any different that @Value is that possible? – chiperortiz Feb 09 '23 at 18:52
  • 1
    Short answer, yes you can. Though if you are using a spring application I would not recommend it. It was designed this way so the framework can get you the values you need from the correct resources. Now if you still need to get that property you can always read the property file directly and then get it using load resources here: https://stackoverflow.com/a/8285636/460557 – Jorge Campos Feb 09 '23 at 19:00
  • You can also try injecting the Environment bean using @Autowired and then try reading the property. – Shivam... Feb 09 '23 at 19:04

1 Answers1

1

This should work...

import org.springframework.core.env.Environment;

@Component
class WithEnvironment {

    WithEnvironment(Environment environment) {
        System.out.println(environment.getProperty("stackoverflow.questiontitle"));
    }
}

To see the value in IntelliJ IDEA in debug mode you can use:

  • ((ApplicationEnvironment)environment).getProperty("stackoverflow.questiontitle")

  • add a New Class Level Watch... on environment with getProperty("stackoverflow.questiontitle")


enter image description here

Dirk Deyne
  • 6,048
  • 1
  • 15
  • 32