Spring 多线程下注入 bean 问题详解

问题

Spring中多线程注入userThreadService注不进去,显示userThreadService为null异常

代码如下:

1

2

3

4

5

6

7

8

扫描二维码关注公众号,回复: 19410 查看本文章

9

10

public class UserThreadTask implements Runnable {

  @Autowired

  private UserThreadService userThreadService;

  @Override

  public void run() {

    AdeUser user = userThreadService.get("0");

    System.out.println(user);

  }

}

解决方案一

把要注入的Service,通过构造传过去,代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

public class UserThreadTask implements Runnable {

  private UserThreadService userThreadService;

  public UserThreadTask(UserThreadService userThreadService) {

    this.userThreadService = userThreadService;

  }

  @Override

  public void run() {

    AdeUser user = userThreadService.get("0");

    System.out.println(user);

  }

}

1

2

Thread t = new Thread(new UserThreadTask(userThreadService));

t.start();

解决方案二

通过ApplicationContext中获取需要使用的Service

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

import org.springframework.beans.BeansException;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

public class ApplicationContextHolder implements ApplicationContextAware {

  private static ApplicationContext context;

  @Override

  public void setApplicationContext(ApplicationContext context) throws BeansException {

    ApplicationContextHolder.context = context;

  }

  //根据bean name 获取实例

  public static Object getBeanByName(String beanName) {

    if (beanName == null || context == null) {

      return null;

    }

    return context.getBean(beanName);

  }

  //只适合一个class只被定义一次的bean(也就是说,根据class不能匹配出多个该class的实例)

  public static Object getBeanByType(Class clazz) {

    if (clazz == null || context == null) {

      return null;

    }

    return context.getBean(clazz);

  }

  public static String[] getBeanDefinitionNames() {

    return context.getBeanDefinitionNames();

  }

}

Spring 加载自己定义的ApplicationContextHolder类

1

<bean class = "cn.com.infcn.applicationcontext.ApplicationContextHolder"></bean>

根据 bean 的名称获取实例

复制代码代码如下:
UserService user = (UserService) ApplicationContextHolder.getBeanByName("userService"); 

根据 bean 的Class 获取实例(如果该Class存在多个实例,会报错的)

复制代码代码如下:
UserService user = (UserService) ApplicationContextHolder.getBeanByType(UserService.class); 

这种方式,不管是否多线程,还是普通的不收spring管理的类,都可以使用该方法获得spring管理的bean。

猜你喜欢

转载自my.oschina.net/u/3764794/blog/1626292
今日推荐