'How to use Autowired in BeforeStep cucumber step definition

I'm getting NullPointerException when I use @Autowired in the @BeforeStep cucumber method in my step definition. What I'm doing wrong here?

Please find my code below:

RunTest.java

import io.cucumber.junit.platform.engine.Cucumber;

@Cucumber
public class RunTest {
}

CucumberSpringConfig.java

import io.cucumber.spring.CucumberContextConfiguration;
import org.springframework.boot.test.context.SpringBootTest;


@CucumberContextConfiguration
@SpringBootTest(classes = DemoApplication.class)
public class CucumberSpringConfig {
}

MyStepdefs.java

import io.cucumber.java.BeforeStep;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
    
    public class MyStepdefs {
            
        //@Autowired Environment environment;
        
        Environment environment;
        
        MyStepdefs(Environment environment) {
            this.environment = environment;
        }
            
    @BeforeStep
    public static void beforeStep() {
    System.out.println("beforeStep method");
    String path = environment.getProperty("spring.security.oauth2.token-uri");
    System.out.println("path: " +path);
    }
    }

pom.xml

<!-- cucumber plugins -->
            <dependency>
                <groupId>io.cucumber</groupId>
                <artifactId>cucumber-java</artifactId>
                <version>6.6.1</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>io.cucumber</groupId>
                <artifactId>cucumber-junit</artifactId>
                <version>6.6.1</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>io.cucumber</groupId>
                <artifactId>cucumber-spring</artifactId>
                <version>6.6.1</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>io.cucumber</groupId>
                <artifactId>datatable</artifactId>
                <version>3.4.0</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>io.cucumber</groupId>
                <artifactId>cucumber-junit-platform-engine</artifactId>
                <version>6.6.1</version>
                <scope>test</scope>
            </dependency>

Exception:

Step failed java.lang.NullPointerException at com.demo.test.step.MyStepdefs.beforeStep(MyStepdefs.java:33)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source