spring框架 在Util一般工具类中加载spring中的Bean对象(服务类等)

准备工作

在一般的Util工具类中,并没有 spring中的 @component 等注解,不能直接使用spring 的注入,一般的成员属性可能均为静态成员属性,包括对外提供的方法也都是静态的,而如果我们想在Util工具类使用被 @service 某一服务模块的对象显然是不能直接引用的,一方面是加载顺序的,一方面并不支持注入。

此时可以再添加一个用于获取 Spring bean的中间工具类,间接获取 spring 中的bean

添加如下:

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

@Component
public final class SpringTool implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(Class clazz) {
        return getApplicationContext().getBean(clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringTool.applicationContext == null) {
            SpringTool.applicationContext = applicationContext;
        }
    }
}

@Component 可以不要

在Util中的引用方式

public class TransCatalogUtil {

	// 一般静态成员
    private static final String Const1 = "Const1";
    private static final String Const2 = "Const2";
    
    // spring中的bean引入
    private static IServiceTypeService serviceTypeService = (IServiceTypeService) SpringTool.getBean("ServiceTypeService");

	.......
	.......
}

这里的服务类在项目中的声明

@Service("ServiceTypeService")
public class ServiceTypeService implements IServiceTypeService {
	...........
}

这样引用后即可在util中写入spring容器中的bean

还有一种方式见下面的连接
另一种静态方法中写入spring 的bean

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值