I have a Spring Boot application with the following structure:
- com.test (Root Class)
- com.test.jpa (JPA Entities and Repositories)
- com.test.netty (netty TCP server)
The root class is:
@ComponentScan(basePackages = {"com.test"})
//@EnableJpaRepositories
//@EntityScan
public class MyApplication {
...
The Netty Server:
package com.test.netty;
@Service
@Slf4j
public class NettyServer {
private EventLoopGroup boss = new NioEventLoopGroup();
private EventLoopGroup work = new NioEventLoopGroup();
@PostConstruct
public void start() {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boss, work).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port))
// .option(ChannelOption.SO_BACKLOG, 1024)
.handler(new LoggingHandler(LogLevel.INFO)).childOption(ChannelOption.SO_KEEPALIVE, true)
.childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ServerChannelInit());
try {
ChannelFuture future = bootstrap.bind().sync();
if (future.isSuccess()) {
log.info("Netty Server Started!");
}
} catch (InterruptedException ie) {
log.error("Error Initializing Netty Server. Error: " + ie.getMessage());
}
}
@PreDestroy
public void destroy() throws InterruptedException {
boss.shutdownGracefully().sync();
work.shutdownGracefully().sync();
log.info("Netty Server Shut Down!");
}
and:
public class ServerChannelInit extends ChannelInitializer<SocketChannel>{
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("mainHandler", new ServiceHandler());
}
and:
package com.test.netty;
@Component
public class ServiceHandler extends ChannelInboundHandlerAdapter {
private SomeEntity en;
@Autowired
SomeRepository sr;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// Read data and persist some entitys using injected repository
And repository:
package com.test.jpa;
//@Repository
public interface SomeRepository extends JpaRepository<SomeEntity, BigInteger> {
}
The problem is: Repository is not injected into com.test.netty classes. I use it in root class and in JUnit tests without any problem. I added @Repository to the repository and also added repo packages in @EnableJPARepositories but nothing changed.
Any ideas?
...
afterServerBootstrap bootstrap = new ServerBootstrap();
. How are you registering the handler with theServerBootstrap
? There is noServiceHandler
autowired intoNettyServer
(unless there's setter injection going on and you also left that part out), so how are you obtaining the reference to theServiceHandler
bean? – crizzis