• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
攻城狮的世界我不懂——lmky
梦想还是要有的!
博客园    首页    新随笔    联系   管理    订阅  订阅
Spring普通类/工具类获取并调用Spring service对象的方法

参考《Spring普通类获取并调用Spring service方法》,网址:https://blog.csdn.net/jiayi_0803/article/details/68924558

在Spring MVC中,Controller中使用service只需使用注解@Resource/@Autowired就行,但是一般类(即不使用@Controller注解的类)要用到service时,Spring中的Service通过new实例化的对象脱离了Spring容器的管理,获取不到注解的属性值,所以会是null,就算调用service的类中有@Component注解加入了Spring容器管理,也还是null.
---------------------
1、创建获取Spring的工具类SpringUtil


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


//创建获取Spring的工具类,用于Spring普通类或工具类获取并调用Spring service对象
public class SpringUtil implements ApplicationContextAware{
  private static ApplicationContext appCtx;
  @Override
  public void setApplicationContext(ApplicationContext applicationContext)
  throws BeansException {
    appCtx = applicationContext;
  }
  public static ApplicationContext getApplicationContext() {
    return appCtx;
  }
  public static Object getBean(String beanName) {
    return appCtx.getBean(beanName);
  }
}


2、通过用@Service("xxService")在service层声明service类

@Service("xxService")
public interface xxService {

}

注意不是impl实现类

3、通过@Resource在普通类或工具类中获取对象并调用service

@Resource
private xxService xxService;// Service接口
//用SpringUtil.getBean("xxService")的形式获取并调用service
xxService = (xxService) SpringUtil.getBean("xxService");


4、在applicationContext.xml 中声明该Spring工具类

  <!-- Spring工具类 -->
  <bean id = "springUtil"  name="springUtil" class="com.xx.util.SpringUtil"/>

 

posted on 2018-12-19 15:57  limeiky  阅读(5601)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3