springboot使用反射后@Autowired 失效问题解决

比眉伴天荒 2023-09-23 13:40 175阅读 0赞

我写在注释里面了,看看能不能看懂

  1. //通过反射获得类对象,注意不能 new 否则为空
  2. Class<?> aClass = Class.forName("com.seven.handlers." + s);
  3. String simpleName = aClass.getSimpleName();
  4. //类名前缀大写转换
  5. String firstLowerName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);
  6. /**
  7. * 只会扫描带@Component注解的
  8. */
  9. Object obj = MianMianApplication.SpringContextUtil.getBean(firstLowerName, aClass);
  10. 此时的OBj就是咱们想要的反射

配置文件如下

  1. @Component
  2. @Lazy(value=false)
  3. public static class SpringContextUtil implements ApplicationContextAware {
  4. // Spring应用上下文环境
  5. private static ApplicationContext applicationContext;
  6. /**
  7. * Spring容器启动后,会把 applicationContext 给自动注入进来,然后我们把 applicationContext 赋值到静态变量中,方便后续拿到容器对象
  8. */
  9. @Override
  10. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  11. SpringContextUtil.applicationContext = applicationContext;
  12. }
  13. /**
  14. * @return ApplicationContext
  15. */
  16. public static ApplicationContext getApplicationContext() {
  17. return applicationContext;
  18. }
  19. /**
  20. * 获取对象
  21. *
  22. * @param name
  23. * @return Object
  24. * @throws BeansException
  25. */
  26. public static Object getBean(String name) throws BeansException {
  27. return applicationContext.getBean(name);
  28. }
  29. public static Object getBean(String name, Class cla) throws BeansException {
  30. return applicationContext.getBean(name, cla);
  31. }
  32. }

发表评论

表情:
评论列表 (有 0 条评论,175人围观)

还没有评论,来说两句吧...

相关阅读

    相关 @Autowired 失效

    @Autowired 失效 如果类B中存在成员属性p, p是通过@Autowired自动注入,而类B的实例是通过new的方式产生的,那么自动注入会失效的 比方说,有一个