简体   繁体   中英

Injecting concrete class in Spring that needs to subclass a framework type

I have a concrete type that extends types from the Netty framework:

public class ServerHandlerImpl extends ChannelInboundHandlerAdapter implements ServerHandler

ChannelInboundHandlerAdapter implements ChannelInboundHandler

When I create ServerHandlerImpl, I want to use Spring to inject it. I know I can use the concrete type. But I was unsure if there was a way to inject from the interface.

ServerHandler interface right now is empty:

public interface ServerHandler {
}

When I try to inject the type from the interface,

@Autowired
private ServerHandler serverHandler;

@Override
protected void initChannel(Channel ch) throws Exception {
    pipeline.addLast(serverHandler);  
}

It will not compile because the addLast is looking for a type that implements ChannelInboundHandler, which my concrete type does, but the interface does not. What do people do in these situations?

Well this has nothing to do with Spring but with Java and OO programming.

You declare having an object of type ServerHandler and try to pass it to a method pipeline.addLast that I guess is expecting an object of type io.netty.channel.ChannelHandler. ServerHandler is not child of ChannelHandler so the compiler can't accept that has it has no guarantee that the real instance it will receive at runtime will be child of ChannelHandler.

This is simple OO concept. Here I don't understand why you would declare your field as ServerHandler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM