zoukankan      html  css  js  c++  java
  • 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"/>

     

  • 相关阅读:
    LeetCode 226. Invert Binary Tree
    LeetCode 221. Maximal Square
    LeetCode 217. Contains Duplicate
    LeetCode 206. Reverse Linked List
    LeetCode 213. House Robber II
    LeetCode 198. House Robber
    LeetCode 188. Best Time to Buy and Sell Stock IV (stock problem)
    LeetCode 171. Excel Sheet Column Number
    LeetCode 169. Majority Element
    运维工程师常见面试题
  • 原文地址:https://www.cnblogs.com/limeiky/p/10143789.html
Copyright © 2011-2022 走看看