我有一个spring boot应用程序,其结构如下:
com.test(根类)
com.test.jpa(jpa实体和存储库)
com.test.netty(netty tcp服务器)
根类是:
@ComponentScan(basePackages = {"com.test"})
//@EnableJpaRepositories
//@EntityScan
public class MyApplication {
...
netty服务器:
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!");
}
以及:
public class ServerChannelInit extends ChannelInitializer<SocketChannel>{
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("mainHandler", new ServiceHandler());
}
以及:
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
和存储库:
package com.test.jpa;
//@Repository
public interface SomeRepository extends JpaRepository<SomeEntity, BigInteger> {
}
问题是:存储库没有注入com.test.netty类。我在根类和junit测试中使用它,没有任何问题。我将@repository添加到存储库中,并在@enablejparepositories中添加了repo包,但没有任何更改。
有什么想法吗?
2条答案
按热度按时间qojgxg4l1#
我刚刚执行了以下内容,只需添加
@SpringBootApplication
在你的主课上。取消注解@Repository
```@SpringBootApplication
public class MyApplication {
}
@Repository
public interface SomeRepository extends JpaRepository<Person, BigInteger> {
}
@Component
public class SampleRepo implements SomeRepository{
}
@RestController
public class ServiceHandler {
}
ki1q1bka2#
如果你要创建一个
ServiceHandler
当然不会执行依赖注入,而不是使用spring为您创建的bean示例。你需要注射ServiceHandler
豆成ServerChannelInit
以及制造ServerChannelInit
一@Component
本身:然后注射
ServerChannelInit
进入NettyServer
: