在spring应用程序中,我们这样编写以通过手动加载spring应用程序上下文来获取bean.
ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml");
JobLauncher launcher=(JobLauncher)context.getBean("launcher");
Run Code Online (Sandbox Code Playgroud)
如何在春季靴子做类似的事情?作为一个新手...需要帮助
Evg*_*rov 15
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用xml文件来声明bean而不是java配置,只需使用即可 @ImportResource({"classpath*:applicationContext.xml"})
编辑:回答注释:使util类成为一个spring bean(使用@Component注释和组件扫描或如上SomeClass所示),然后你可以@Autowire你喜欢的bean.然后,当您想要使用Util类时,只需从上下文中获取它.
| 归档时间: |
|
| 查看次数: |
15997 次 |
| 最近记录: |