// app
@SpringBootApplication
public class App {
public static void main(String[] args) {
ConfigurableApplicationContext configurableContext = SpringApplication.run(App.class, args);
AppContext.getInstance().setContext(configurableContext);
var beanFactory = configurableContext.getBeanFactory();
beanFactory.registerSingleton("someSingletone", new SomeSingletonBean());
var test = new Test();
test.execute();
}
}
class Test{
public void execute(){
var someSingleTone = (SomeSingletonBean) AppContext.getInstance().getContext().getBean("someSingletone");
someSingleTone.sayHello();
}
}
// someSingletoneBean
public class SomeSingletonBean {
public void sayHello(){
System.out.println("hello");
}
}
// helper singletone class
package com.example.main;
import org.springframework.context.ApplicationContext;
/**
* @author Dinesh.Lomte
*
*/
public enum AppContext {
INSTANCE;
public static AppContext getInstance() {
return INSTANCE;
}
private ApplicationContext applicationContext;
/**
* Default constructor
*/
private AppContext() {
}
/**
*
*/
public void setContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
/**
*
* @return
*/
public ApplicationContext getContext() {
return applicationContext;
}
}