[英]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. 在spring应用程序中,我们这样编写以通过手动加载spring应用程序上下文来获取bean。
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 作为一个新手...需要帮助
@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"})
您也可以使用xml文件来声明bean而不是java配置,只需使用@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. 编辑:回答评论:将util类设为spring bean(使用@Component注释和组件扫描或与上面显示的SomeClass
相同)然后你可以@Autowire你喜欢的bean。 Then when you want to use the Util class just get it from the context. 然后,当您想要使用Util类时,只需从上下文中获取它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.