静态工具类中使用注解注入service

来源:互联网 发布:gson遍历未知json key 编辑:程序博客网 时间:2024/06/02 04:09

一般需要在一个工具类中使用@Autowired 注解注入一个service。但是由于工具类方法一般都写成static,所以直接注入就存在问题。

使用如下方式可以解决:

/**
 *
 */
package com.spring.drive.common.util;

import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.spring.drive.service.AutowiredStatic;


/**
 * className:OpeLogUtils
 *
 * 管理员操作日志
 *
 * @author pengyh
 * @version 1.0.0
 * @date 2014-07-10 09:04:48
 *
 */
@Component
public class AutowiredStatic{

    private static Logger logger = LoggerFactory.getLogger(AutowiredStatic.class);

    @Autowired
    private AutoeiredService autoeiredService ;
    private static AutowiredStatic autowiredStatic;

    public void setAutoeiredService(AutoeiredServiceautoeiredService) {
        this.autoeiredService=autoeiredService;
    }
   

    /**

    *

    *关于在spring  容器初始化 bean 和销毁前所做的操作定义方式有三种:

    *第一种:通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作

    *第二种是:通过 在xml中定义init-method 和  destory-method方法

    *第三种是: 通过bean实现InitializingBean和 DisposableBean接口

    */

    @PostConstruct
    public void init() {
        autowiredStatic= this;
        autowiredStatic.autoeiredService= this.autoeiredService;

    }

    /**
     * 静态方法使用spring注解获取到的对象
     */
    public static void main(String[] args) {

        //使用注解对象调用方法

       autowiredStatic.autoeiredService.findAllData();

    }
}



原创粉丝点击