我只是从DI和Spring开始。我有这两个组件(伪代码)

@Component
public class AuthHandlerImpl extends ChannelInboundHandlerAdapter implements AuthHandler {

    @Autowired
    AuthService authService;

    @Override
    channelRead(ChannelHandlerContext ctx, Object msg) {
        authService.authenticate(msg);  // want to pass ctx to constructor of authService
    }
}

@Component
public class AuthServiceImpl implements AuthService {

    private CustomerService customerService;

    private ChannelHandlerContext ctx;

    @Autowired
    public AuthServiceImpl(CustomerService customerService, ChannelHandlerContext ctx) {
        this.customerService = customerService;
        this.ctx = ctx;
    }
}


我要实现的目标是在AuthService中注入构造函数参数,其中构造函数参数之一是ChannelInboundHandlerAdapter类的ChannelHandlerContext。不知道这是否可能。

最佳答案

是的,这是可能的,但是必须将CustomerService和ChannerHandlerContext定义为spring bean(例如@ Component,@ Service,@ Controller或@Bean批注),以便在构造函数中自动装配。您可以检查this发布以获取有关该主题的更多信息。

09-12 22:30