博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring普通类/工具类获取并调用Spring service对象的方法
阅读量:7282 次
发布时间:2019-06-30

本文共 1391 字,大约阅读时间需要 4 分钟。

参考《Spring普通类获取并调用Spring service方法》,网址:

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"/>

 

转载地址:http://pfkjm.baihongyu.com/

你可能感兴趣的文章
tomcat部署乱码
查看>>
网络安全小实验
查看>>
1月30日
查看>>
forClass
查看>>
每一个关注支付的人都在这里
查看>>
百晓生带你玩转linux系统服务搭建系列-----搭建DHCP服务和中继代理
查看>>
GMO Media 使用 HashiCorp Terraform Enterprise 自动配置基础
查看>>
了解java虚拟机&mdash;CMS回收器(8)
查看>>
Lambda plus: 云上大数据解决方案
查看>>
51.使用jdbc操作数据库
查看>>
厉害了!莱西一智能科技企业连获三个智慧城市优秀解决方案
查看>>
springboot mybatis 框架整合源码 集成代码生成器 shiro 权限
查看>>
网页中显示数学公式
查看>>
利用TortoiseGit(小乌龟)将项目上传至GitHub网站
查看>>
令一个内容为数字字符串转换为对应的数字
查看>>
day18集合便利删除
查看>>
极简主义!让手机壁纸,惊现高级脸Feel~
查看>>
解决SQLite database is locked
查看>>
JAVA 添加、修改和删除PDF书签
查看>>
怎样配置主从同步结构
查看>>