提问者:小点点

Spring Boot不会将@了的存储库注入到netty类中


我有一个具有以下结构的 Spring 启动应用程序:

  • 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中添加了存储库包,但没有任何变化。

有什么想法吗?


共2个答案

匿名用户

如果您自己创建< code>ServiceHandler的实例,而不是使用Spring为您创建的bean实例,当然不会执行依赖注入。您需要将< code>ServiceHandler bean注入到< code>ServerChannelInit中,并使< code>ServerChannelInit成为< code>@Component本身:

@Component
public class ServerChannelInit extends ChannelInitializer<SocketChannel>{

    private final ServiceHandler handler;

    public ServerChannelInit(ServiceHandler handler) {
        this.handler = handler;
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline().addLast("mainHandler", handler);
        
    }
    ...
}

然后将 ServerChannelInit 注入 NettyServer

@Service
@Slf4j
public class NettyServer {

    private final ServerChannelInit channelInit;

    public NettyServer(ServerChannelInit channelInit) {
        this.channelInit = channelInit;
    }

    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(channelInit);
...
}

匿名用户

我刚刚执行了以下代码,只需在主类中添加< code > @ spring boot application 。取消注释< code>@Repository

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

@Repository
public interface SomeRepository extends JpaRepository<Person, BigInteger> {

     void foo();
}


@Component
public class SampleRepo implements SomeRepository{

    @Override
    public void foo() {
        System.out.println("Called...." );
    }
}
@RestController
public class ServiceHandler  {


    @Autowired
    private SomeRepository sr;

    @GetMapping("/hello")
    public void call(){
        sr.foo();

    }
}

它起作用了!