加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

手动加载应用程序上下文以在spring启动应用程序中编写getBean()

发布时间:2020-12-15 01:32:07 所属栏目:大数据 来源:网络整理
导读:在spring应用程序中,我们这样编写以通过手动加载spring应用程序上下文来获取bean. ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml");JobLauncher launcher=(JobLauncher)context.getBean("launcher");

在spring应用程序中,我们这样编写以通过手动加载spring应用程序上下文来获取bean.

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

如何在春季靴子做类似的事情?
作为一个新手…需要帮助

最佳答案
@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 

您也可以使用xml文件来声明bean而不是java配置,只需使用@ImportResource({“classpath *:applicationContext.xml”})

编辑:回答评论:将util类设为spring bean(使用@Component注释和组件扫描或与上面显示的SomeClass相同)然后你可以@Autowire你喜欢的bean.然后,当您想要使用Util类时,只需从上下文中获取它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读