在非Spring管理的类中注入Bean

1.2k 词

在Spring管理的类中注入Bean对象非常容易,只需使用@Autowired或者@Resource注解即可,但是在非Spring管理的对象中,注入Bean对象却没这么简单。

这时,我们就需要自己写一个工具类了,实现很简单,代码如下:

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.hmdp.utils;

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

@Component
public class BeanHelper implements ApplicationContextAware {
private static ApplicationContext context;

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

/**
* 根据name获取Bean
* @param name Bean的名字
* @return Bean
*/
public static Object getBean(String name) {
return context.getBean(name);
}

/**
* 根据class获取bean
* @param clazz 类型
* @return bean
* @param <T> bean的类型
*/
public static <T> T getBean(Class<T> clazz) {
return context.getBean(clazz);
}

/**
* 根据name和class获取bean
* @param name 名字
* @param clazz 类型
* @return bean
* @param <T> bean的类型
*/
public static <T> T getBean(String name, Class<T> clazz) {
return context.getBean(name, clazz);
}
}