'Not able to get application context object using ApplicationContextAware

i have a microservice application developed using spring boot. i also have a project under under the same application which contains some java classes (non spring classes). i am trying to use some of the beans which are available in the spring container in this non java class using the ApplicationContextAware approach. when i debug the code during the bootrun, i can see the setApplicationContext(ApplicationContext ctx) is getting call and the context is getting set.

when from inside my non spring java class when i tried to get the instance of the context using the public static getApplicationContext(), i am getting null for context.

below is the sample example i had used.

@Component
public class ApplicationContextProvider implements ApplicationContextAware {
    private static ApplicationContext context;

    public ApplicationContext getApplicationContext() {
        return context;
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) {
        context = ctx;

    }
}

this is how i try to get the instance

ApplicationContext  c = ApplicationContextProvider.getApplicationContext();

i am not able to figure it out what is missing here, as i am using spring boot, i dont think there is a need to configure any bean in xml.



Solution 1:[1]

This worked for me with your code. I could get the application start time after fetching the provider from the context.

@RestController
public class SampleController {


    @Inject
    ApplicationContextProvider provider;

    @RequestMapping(value = "..", method = RequestMethod.GET)
    public ResponseEntity<String> someMethod() throws IOException {
        ApplicationContext  c = provider.getApplicationContext();
        System.out.println(c.getApplicationName());
        c.getStartupDate()
    }
}

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 piy26