zoukankan      html  css  js  c++  java
  • spring学习——注入静态对象属性

      spring注入静态对象属性时,因为虚拟机类加载问题,直接在属性上使用@Autowired 是不可以的。需要在属性对应的set方法上@Autowired,并且,set方法不能定义为static。

    1.创建静态对象属性对应的类

    package com.bluej.springj.service.impl;
    
    import org.springframework.stereotype.Service;
    
    import com.bluej.springj.service.LogService;
    
    @Service("logService")
    public class LogServiceImpl implements LogService {
    
        public void doLog() {
            System.out.println("LogServiceImpl.doLog");
    
        }
    
    }
    LogService类代码

    2.创建spring使用的对象

     1 package com.bluej.springj.service.impl;
     2 
     3 import org.springframework.beans.factory.annotation.Autowired;
     4 import org.springframework.stereotype.Service;
     5 
     6 import com.bluej.springj.service.CheckService;
     7 import com.bluej.springj.service.LogService;
     8 
     9 @Service("checkService")
    10 public class CheckServiceImpl implements CheckService {
    11     
    12     private static LogService logService;
    13 
    14     public boolean doCheck(Object obj) {
    15         System.out.println("CheckServiceImpl.doCheck");
    16         logService.doLog();
    17         return false;
    18     }
    19 
    20     @Autowired
    21     public  void setLogService(LogService logService) {
    22         CheckServiceImpl.logService = logService;
    23     }
    24 }
    CheckServiceImpl 类

    3.调用示例

     1 package com.bluej.springj.start;
     2 
     3 import org.springframework.context.ApplicationContext;
     4 import org.springframework.context.support.ClassPathXmlApplicationContext;
     5 
     6 import com.bluej.springj.service.CheckService;
     7 
     8 public class Main {
     9     public static void main(String[] args) {
    10         ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    11         CheckService checkService = applicationContext.getBean("checkService", CheckService.class);
    12         checkService.doCheck(new Object());
    13     }
    14 }
    Main类

    4.代码地址

    git地址:https://git.oschina.net/blue_phantom/ssmj.git

    项目名称:springj

    包位置:package com.bluej.springj.start

    执行测试类:Main.java

  • 相关阅读:
    HDU1496(巧妙hash)
    SPOJ(后缀数组求不同子串个数)
    django-admin自定义登录
    Bootstrap实现的页面
    ImageMagick来处理图片,缩放,调整高度等操作
    xlrd,xlwt操作Excel实例
    匹配图片修改图片名称
    python 的两个模块xlwt,xlrd,写入和读取Excel数据
    Excel常见操作,重复数据,去除数据关联
    Excel数据常用操作,vlookup,text,trim,数据格式导致出错
  • 原文地址:https://www.cnblogs.com/bluej/p/6594249.html
Copyright © 2011-2022 走看看