在不是控制层里面controller里面使用service或者dao。可以讨论一下

    首先说一下ApplicationContext这个类,bean工厂,applicationContext说白了就是对beanFactory的扩展,也就是一个spring容器,而且applicationContext是单例的。

      配置一下,就这么一句话在spring里面

<bean class="com.prj.utils.mUtils.SpringTool"/>

然后在你的代码里面设置一下就ok了

private static YordergoodsService yordergoodsService =(YordergoodsService)UfdmContextHelperUtil.getBean("yordergoodsServiceImpl");
	

 

然后你启动项目就能在你的工具类或者其他地方直接调service

=================================================================================

经过楼主学习发现上面的方式 用起来比较简单但是总缺了点什么,现在补充点知识

package org.springframework.context;
//spring里面有这个接口提供扩展
public interface ApplicationContextAware extends Aware {
	void setApplicationContext(ApplicationContext applicationContext) throws BeansException;

}

然后继承这个类重写这个方法SpringBeanUtil 

package com.mxc.web.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringBeanUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public SpringBeanUtil() {
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtil.applicationContext = applicationContext;
    }

    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> type) {
        return applicationContext.getBean(type);
    }

    public static ApplicationContext getContext() {
        return applicationContext;
    }
}

当你拿到了applicationContext的时候你就可以调用里面的方法为所欲为

当然上面那个类要被spring扫到不然读取不了,如果是springboot的则放到同级目录或者子级下,或者手动 @import加载。

反正你要他成为bean就行了

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值