java - spring如何在一个普通的类访问到Service的方法呢?
伊谢尔伦
伊谢尔伦 2017-04-18 09:40:49
[Java讨论组]

例如,下面的代码,只是一个普通类,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;
    }

}
伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(3)
巴扎黑

`ApplicationContext applicationContext=new ClassPathXmlApplicationContext("");

    applicationContext.getBean("");`

是这样吗

黄舟

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

PHP中文网

单例模式 getBean(service)

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号