Skip to content

How can i fetch property from file in Java class?

I have set the variable “” in my environment to “test” and I have below file in my src/main/resources.

It has one property “machine”


I want to access this property in one of my Java based class.

package com.test.service;

public class TestMachine {

    private String machineName;

    public void checkMachine() {

PropertiesConfig class:

public class PropertiesUtils {

    public static void initProperties() {
        String activeProfile = System.getProperty("");
        if (activeProfile == null) {
            activeProfile = "test";
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        Resource[] resources = new ClassPathResource[] {new ClassPathResource(""),
                        new ClassPathResource("application-" + activeProfile + ".properties")};

But while running this as a Spring boot application in Eclipse. I am getting below error:

Error creating bean with name 'TestMachine': Injection of autowired dependencies failed;

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'machineName' in value "${machineName}" at org.springframework.util.PropertyPlaceholderHelper.parseStringValue( ~[spring-core-5.3.9.jar:5.3.9]

What am I missing? I found this way only in most of the websites.



To give you a better answer please show your and the full stacktrace, but this may help.

You can get the current profile using the Environment class.

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import org.springframework.core.env.Environment;

public class DemoApplication {

  Environment env;

  public static void main(String[] args) {, args);

  public CommandLineRunner run() {
    return new CommandLineRunner() {

      public void run(String... args) {
        for (var  p: env.getActiveProfiles()) {


And pass the profile via cli

use this

mvn spring-bot:run


gradle bootRun --args "''"


java -jar *.jar