I'm trying to use Brave Tracer Inside the non component class. This code is working fine in main project, setting context and getting context both are printing. But when I generate jar file and import it to different project 2 and run it, Only Getting context is printing and getting null error.
I'm new to spring-boot Initial problem was I wanted to Autowired Tracer to my non-component class, I google it to solve this problem, I got this result in google. If any one have any other solution for this kind of problem. Open to suggestion
Thank you.
// Project 1
// This is the main code, Generated a Jar file
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext ctx;
@Override
public void setApplicationContext(ApplicationContext appContext) {
System.out.println("Setting context");
ctx = appContext;
}
public static ApplicationContext getApplicationContext() {
System.out.println("Getting context");
return ctx;
}
}
// Project 2
// imported project 1 jar file to this project
// Added jar file below main package
// for simplicity i have used this in main class which is component class
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
// using this lines in non-component class
ApplicationContext contextUtils = ApplicationContextUtils.getApplicationContext();
contextUtils.getApplicationName();
}
}
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "org.springframework.context.ApplicationContext.getApplicationName()" because "contextUtils" is null
at com.omniauth.omniauth.OmniAuthApplication.main(OmniAuthApplication.java:26)
You are getting the
NullPointerExceptionbecause the code in the other project is callinggetApplicationContextbefore theApplicationContextUtilshas been loaded.In fact, the
ApplicationContextUtilscomponent may not be loaded at all, as by default, Spring Boot only loads components that are in the same package (or subpackages) as the main class (the one annotated with@SpringBootApplication). If the other project uses different package names,ApplicationContextUtilsis never loaded.