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

标签 java spring

我刚刚开始使用 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/

相关文章:

java - 四元数 "regular rotation"在转换为轴角时给出陌生人值

spring - 使用Spring Security插件使用文件扩展名内容协商?

Java Socket 无法使用 NoRouteToHostException 而不是 ConnectionRefused 连接到 "0.0.0.0"

java - 向 Web 服务发出 POST 请求

java - 将 java.sql.Timestamp 转换为 javax.xml.datatype.XMLGregorianCalendar 而不会丢失 nanos

java - 在java中使用stacks(LinkedList)实现表达式树如下,但有错误

java - 理论: Two system integration through web service

java - 3.0 中的 Spring SimpleFormController

java - @Transactional 问题以及如何与@Service 一起使用

javascript - 如何在没有表单的情况下提交动态数据?