在Spring框架中, 某些类可能并没有被添加@Component注解标记成一个容器, 那么这个类中是没有办法注入其他容器的, 这时候就需要使用到ApplicationContextAware接口来帮助我们进行容器的注入
重写setApplicationContext来获取ApplicationContext对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| @Component public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext;
@Override public void setApplicationContext(ApplicationContext context) throws BeansException { SpringContextHolder.applicationContext = context; }
public static <T> T getBean(Class<T> requiredType) { return applicationContext.getBean(requiredType); }
public static <T> T getBean(String name) { return (T) applicationContext.getBean(name); } }
|
调用方式如下:
1 2 3 4 5 6 7 8 9 10 11
| public class UserUtils {
private static final UserService userService = SpringContextHolder.getBean("userService");
public static User getUser(String id){ return userService.findById(id); } }
|
参考:
- https://juejin.cn/post/7157006255779741733