Spring依赖注入,在main方法或junit测试类里获取得Spring容器

学spring入门的时候就得先学会使用如何在普通的javabean里获取application.xml中配置的bean

java:

  ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
  BeanFactory factory = (BeanFactory) context;
  UserServiceImpl userservice = (UserServiceImpl ) factory.getBean("userservice");

   或者:

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    context.start();
    DemoService demoService = (DemoService) context.getBean("demoService"); // 获取bean
    String hello = demoService.sayHello("world"); // 执行bean方法


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你在Eclipse中创建了一个Spring Boot项目,那么你应该使用Spring Boot的内置工具来运行测试。这些工具可以确保你的测试Spring Boot的上下文中正确运行。你可以按照以下步骤运行测试: 1. 点击项目中的“src/test/java”文件夹,找到你的测试类。 2. 右键单击测试类,选择“Run As”菜单,然后选择“JUnit Test”。 3. 如果你没有看到“JUnit Test”选项,则需要确保你的项目中已经添加了JUnit依赖。你可以在项目的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> ``` 4. 如果你强行启动应用程序并且出现“找不到main方法”的错误,则可能是因为你没有正确配置运行配置。你应该创建一个新的“Spring Boot App”配置,并将其指向你的主应用程序类。你可以按照以下步骤创建和配置此配置: - 点击“Run”菜单,然后选择“Run Configurations”。 - 在左侧面板中,选择“Spring Boot App”。 - 在右侧面板中,单击“New Launch Configuration”按钮。 - 在“Main”选项卡上,选择你的主应用程序类。 - 在“Classpath”选项卡上,选择“Use classpath of project”。 - 单击“Apply”按钮,然后单击“Run”按钮。 如果你按照以上步骤操作,你应该能够成功运行你的Spring Boot测试或应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值