【问题标题】:Find all classes that are not @Autowired查找所有不是@Autowired 的类
【发布时间】:2016-09-10 07:35:10
【问题描述】:

我有一个使用注释的大型 Spring Web 应用程序。但是,有些类使用 @component/service 注释,但不会从调用它们的位置自动装配。而是使用 new 运算符。

我想找出所有使用 new 运算符的用户定义类的实例。

基本上,我创建了一个新的 Http 包装类(弹簧组件),并从应用程序的多个位置调用它。它在某些地方工作是因为自动连接到它的工作是因为包含类和链开头的类是由 spring 管理的。但是在某些地方它不起作用,因为调用链中的一个类是使用 new 实例化的,并且不是 spring 管理的。所以我想解决这个问题,让这些类也由 spring 管理。

我说的是 100 多个课程,所以请建议一种可以在 3-4 小时内完成并防止人为错误的工具或方法。我用eclipse。

例子:

@Component
public class MyHttpClient {

    public int execute() {
        ...
    }
}

@Component
public class UtilC {

    @Autowired
    private MyHttpClient client;

    public int methodC() {
        // When methodC is called from A, it works
        // but when called from B, it gives NullPointerException
        client.execute();
    }
}

@Component
public class UtilB {

    private UtilC c = new UtilC();

    public int methodB() {
        c.methodC();
    }
}

@Component
public class UtilA {

    @Autowired
    private UtilC c;

    public int methodA() {
        c.methodC();
    }
}

请不要这样建议:​​

 @Component
 public class UtilC {

     @Autowired
     private MyHttpClient client;

     public int methodC() {
         try {
             client.execute();
         } catch(NullPointerException npe) {
             new MyHttpClient.execute();
         }
     }
 }

如何搜索所有像 new UtilC 一样实例化的用户定义类

【问题讨论】:

  • 他们的名字是否像SomeService 这样你可以为它写一个正则表达式?
  • 调用层次结构(Ctrl-Alt-H)不能告诉你谁调用了构造函数?如果对象应该是 Spring 管理的,那么除了 Spring 之外,没有人应该调用构造函数,因为 Spring 使用反射来这样做,所以不会显示。如果您没有使用 Call Hierarchy 的构造函数,请临时创建一个。
  • 不,他们没有很好地定义为他们编写正则表达式。我可以在 Eclipse 中搜索使用 new 运算符的用户定义类的实例变量吗?
  • findgrep 的组合应该可以解决问题。阅读手册条目。 (也可能是xargs。)

标签: java eclipse spring-mvc


【解决方案1】:

解决这个问题的一种方法是使用 aspectj(编译时编织)。例如,以下方面允许编译器为使用 @XmlRootElement 用法注释的类的 ctor 创建错误(但在运行时,容器当然可以反射性地调用它)

import javax.xml.bind.annotation.XmlRootElement;

public aspect CtorError {

    declare error : call ((@XmlRootElement *).new(..)) : "ctor called";
}

【讨论】:

    【解决方案2】:

    如果您有“使用注释的大型 Spring Web 应用程序”,则必须使用适当的 Java IDE。每个 IDE 都有这个称为“查找用法”(或类似名称)的功能。你应该使用它。

    例如,使用 Intellij IDEA,我会这样做:

    1. 找到Autowired接口(在源代码中)。使用“查找用法”。
    2. 它应该向您显示用法(根据用法的种类很好地分类)。

    【讨论】:

    • 这将为我提供自动装配的类。它如何给我使用 new 运算符实例化的用户定义的类
    【解决方案3】:

    使用Google reflection 查找所有带有@Autowired 注释的类

    Reflections reflections = new Reflections("org.home.xxx");
    Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(org.springframework.beans.factory.annotation.Autowired.class);
    

    Set 中不存在的类没有注释。

    【讨论】:

    • 我需要知道集合中不存在的所有用户定义的类。
    • 有没有一种方法可以列出我的应用程序中的所有用户定义的类,然后我可以与集合中的类进行比较。如果它们不在集合中,则意味着它们没有自动装配?
    猜你喜欢
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    相关资源
    最近更新 更多