gpt4 book ai didi

java - 带注释的 Spring 依赖注入(inject)

转载 作者:行者123 更新时间:2023-11-30 06:36:43 24 4
gpt4 key购买 nike

我刚刚开始使用 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 注入(inject)构造函数参数,其中构造函数参数之一是来自 ChannelInboundHandlerAdapter 类的 ChannelHandlerContext。不确定这是否可能。

最佳答案

是的,这是可能的,但是 CustomerService 和 ChannerHandlerContext 必须定义为 spring bean(如 @Component、@Service、@Controller 或 @Bean 注释)才能在构造函数中 Autowiring 。您可以查看this发帖以获取有关该主题的更多信息。

关于java - 带注释的 Spring 依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45091060/

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