java - 是否可以让 ObjectProvider 提供来自其他包的对象?

标签 java spring spring-boot javabeans

初始情况

我目前正在使用 Spring 库 PipelinR 构建 API ,其灵感来自著名的 NuGet 包 MediatR 。我在此应用程序中创建了多个包来隔离 java 类。 API 的入口点位于 com.example.project.WebApi 包中。管道的配置文件也位于此处。

@Configuration
public class PipelinrConfiguration {

    @Bean
    Pipeline pipeline(ObjectProvider<Command.Handler> commandHandlers, ObjectProvider<Notification.Handler> notificationHandlers, ObjectProvider<Command.Middleware> middlewares) {
        return new Pipelinr()
          .with(commandHandlers::stream)
          .with(notificationHandlers::stream)
          .with(middlewares::orderedStream);
    }
    
}

无论如何,所有命令和命令处理程序都位于不同的包中,例如com.example.project.ApplicationService.CreateSomethingCommand

com.example.project.ApplicationService.CreateSomething/
    CreateSomethingCommand.java
    CreateSomethingCommandHandler.java

有谁知道我如何在我的 PipelinrConfiguration.java 文件中提供这些类,以便 ObjectProvider 能够找到这些类。

我非常感谢任何形式的帮助,干杯!


编辑:#001

是的,bean 是用 @Component 注释的。

CreateSomethingCommand.java

public class CreateSomethingCommand implements Command<Voidy> {

    public String host;
    
    public CreateSomethingCommand() {
        
    }
    
    public CreateSomethingCommand(String host) {
        this();
        this.host = host;
    }
    
}

CreateSomethingCommandHandler.java

@Component
public class CreateSomethingCommandHandler implements Command.Handler<CreateSomethingCommand, Voidy> {

    @Override
    public Voidy handle(CreateSomethingCommand command) {
        
        System.out.println("Command recieved by " + command.host);
        
        return null;
    }

}

最佳答案

@Configuration
@ComponentScan(basePackages = {"package1”, "package2"})
public class PipelinrConfiguration {
    // attention here you have to declare three different beans of type ObjectProvider otherwise it will inject by type
    @Bean
    Pipeline pipeline(@Qualifier(“bean1”) ObjectProvider<Command.Handler> commandHandlers, @Qualifier(“bean2”)  ObjectProvider<Notification.Handler> notificationHandlers, @Qualifier(“bean3”) ObjectProvider<Command.Middleware> middlewares) {
        return new Pipelinr()
          .with(commandHandlers::stream)
          .with(notificationHandlers::stream)
          .with(middlewares::orderedStream);
    }
    
}

关于java - 是否可以让 ObjectProvider 提供来自其他包的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73387200/

相关文章:

intellij-idea - IntelliJ Spring Boot : How to create an executable jar

Java代理拦截请求

java - Spring /hibernate 。在Web服务中将字符串转换为具有相同时区的日期并插入到SQL中

java - spring social 使用 facebook 登录

java - Spring Boot-Camel-Maven : How to add my own parent Dependency along with Spring Boot Dependency?

java - JPA - Spring Boot - 密码编码

java - Android Activity 未完成并且不启动之前的 Activity

java - Hibernate:无法级联删除子级的单向父级

java - 从内部类引用封闭实例

java - 创建名为 : Injection of autowired dependencies failed, 的 bean 时出错,无法解析占位符