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

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;
    }

}

单例模式 getBean(service)


`ApplicationContext applicationContext=new ClassPathXmlApplicationContext("");

    applicationContext.getBean("");`

是这样吗


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

【热门文章】
【热门文章】