多线程中获取bean对象

https://blog.csdn.net/qq_38493490/article/details/80431321

注:多线程场景下,使用默认的spring自动装配无法获取bean对象,此方案可以从context上下文中直接获取bean。

1、创建类,实现ApplicationContextAware接口;

package com.bond.match.utils;

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

/**
 * Created with IntelliJ IDEA.
 * Date: 2018/1/11 0011
 * Time: 13:20
 * To change this template use File | Settings | File Templates.
 */
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
    private static ApplicationContext context;

    private ApplicationContextProvider(){}

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public  static <T> T getBean(Class<T> aClass){
        return context.getBean(aClass);
    }
}
2、多线程中的调用方式: .method()是bean对象的方法名称

ApplicationContextProvider.getBean(AccountAssetService.class).method()
 

猜你喜欢

转载自blog.csdn.net/lppl010_/article/details/88415526