我对 spring 很陌生(从 PHP 切换到 Java)。
在我的代码中,我有一个 java.lang.reflect.Method
对象,我需要实例化它的类及其所有依赖项。
通常我会在代码中使用 @Autowired
注释,但这是不可能的,因为我的代码获取不同的 Method 对象,而不是特定的类。
问题是 - 如何从依赖容器中获取类实例而不使用注释并且只有类名?
在 php 中,我使用了允许我访问容器的库,我可以通过它的类名获取 DI 服务,如下所示:
$this->container->get('My\Class\Name');
Spring 我尝试过:
@Autowired
private ApplicationContext context;
void myMethod(Method method){
this.context.getBean(method.getClass());
和
this.context.getBean(method.getClass().getName());
这导致了NullPointerException
。
编辑 感谢您的快速回复,
我尝试使用
context.getBean(method.getDeclaringClass());
和
context.getBean(method.getDeclaringClass().getSimpleName());
这也导致了 NullPointerException。
实际上,我的需要是按类或按名称获取该类。我正在尝试为 CQRS 编写自己的命令总线。 让我向您展示一些代码:
处理程序:
public class SimpleCommandBus implements CommandBus {
@Autowired
private ApplicationContext context;
private Map<Class, Method> registry = new HashMap<>();
@Override
public void register(Class c, Method o) {
registry.put(c, o);
}
@Override
public void dispatch(Object command) {
if (!registry.containsKey(command.getClass())) {
throw new CommandDispatchException(String.format("Handler for command %s was not defined.", command));
}
Method method = registry.get(command.getClass());
Object handler = context.getBean(method.getDeclaringClass().getSimpleName());//line causing exception
服务等级:
@Service
public class TestHandler {
public void handle(TestCommand command){
System.err.println(command.getId());
}
}
调用命令总线:
Method method = TestHandler.class.getMethod("handle", TestCommand.class);
TestCommand command = new TestCommand("Test command");
commandBus.register(TestCommand.class, method);
commandBus.dispatch(command);
最佳答案
使用java.lang.reflect.Method.getDeclaringClass()
查找在哪个类中声明了给定方法。 method.getClass()
将返回 method
对象的类型,即 java.lang.reflect.Method
。
@Autowired
AplicationContext ctx;
...
Object bean = ctx.getBean(method.getDeclaringClass());
关于java - Spring Boot - 如何通过名称获取使用 @Service 注释的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52330135/