Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually loading application context to write getBean() in spring boot application

Tags:

spring

In a spring application, we write like this to get a bean through manually loading spring application context.

ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml");
JobLauncher launcher=(JobLauncher)context.getBean("launcher");

How to do the similar thing in spring boot ? Being a newbie...need help

like image 470
pinaki Avatar asked Feb 19 '15 19:02

pinaki


1 Answers

@SpringBootApplication
public class Application {
    public static void main(String[] args) throws Exception {
        ApplicationContext app = SpringApplication.run(Application .class, args);//init the context
        SomeClass myBean = app.getBean(SomeClass.class);//get the bean by type
    }
    @Bean // this method is the equivalent of the <bean/> tag in xml
    public SomeClass getBean(){
         return new SomeClass();
    }

    @Bean 
    public MyUtilClass myUtil(SomeClass sc){
         MyUtilClass uc = new MyUtilClass();
         uc.setSomeClassProp(sc);
         return uc;
    }
}

You can also your xml file to declare the beans instead of the java config, just use @ImportResource({"classpath*:applicationContext.xml"})

Edit: To answer the comment: Make the util class a spring bean(using @Component annotation and component scan or the same as SomeClass shown above) and then you can @Autowire the bean you like. Then when you want to use the Util class just get it from the context.

like image 127
Evgeni Dimitrov Avatar answered Oct 19 '22 06:10

Evgeni Dimitrov