gpt4 book ai didi

java - 查找所有不是@Autowired 的类

转载 作者:行者123 更新时间:2023-12-04 19:33:46 25 4
gpt4 key购买 nike

我有一个使用注释的大型 spring web 应用程序。但是,有些类用 @component/service 注释但不会从调用它们的地方 Autowiring 。相反,使用 new 运算符。

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

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

我说的是 100 多个类(class),所以请推荐一种可以在 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();
}
}
}

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

最佳答案

使用Google reflection查找所有用 @Autowired

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

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

关于java - 查找所有不是@Autowired 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37221275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com