spring如何在一个普通的类访问到Service的方法呢?

例如,下面的代码,只是一个普通类,System.out.println(profitService);这个输出是null

我的spring扫描包有添加这个类所在包的路径:tools就是。

如何能在普通类中调用 spring的service方法?

现在即便在这个类加注解@service或者 @compenent也没用,还是null

    <context:component-scan base-package = "service,tools">
        <context:exclude-filter type = "annotation"
                                expression = "org.springframework.web.bind.annotation.ControllerAdvice" />
        <context:exclude-filter type = "annotation" expression = "org.springframework.stereotype.Controller" />
    </context:component-scan>

public class ExcelTools {


    @Autowired
    private ProfitService profitService;

    public List<Profit> getDataFromExcel(InputStream is) {

        

                if (goalData.size() % 100 == 0) {

                    System.out.println("已经满足1次,保存中。。。。");

                    System.out.println(profitService);
                    System.out.println(goalData);
                    profitService.toSavePartData(goalData);

                    System.out.println("保存完了吗,我要清空了!!!!!");
                    goalData.clear();
                    System.out.println("goalData size:"+goalData.size());

                }
            }

            System.out.println("转换完毕.......");

        } catch (IOException e) {
            e.printStackTrace();
        }

        return goalData;
    }

}
阅读 6.4k
3 个回答
新手上路,请多包涵

`ApplicationContext applicationContext=new ClassPathXmlApplicationContext("");

    applicationContext.getBean("");`

是这样吗

ExcelTools 是spring的bean么。。如果不是spring不能自己帮你做注入处理的,要声明成bean才帮处理。。

单例模式 getBean(service)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题