pinaki
pinaki

Reputation: 331

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

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

Upvotes: 14

Views: 28126

Answers (1)

Evgeni Dimitrov
Evgeni Dimitrov

Reputation: 22516

@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.

Upvotes: 26

Related Questions