简体   繁体   English

Spring Boot 不会将 @Autowired 存储库注入 netty 类

[英]Spring Boot does not inject @Autowired repository into netty classes

I have a Spring Boot application with the following structure:我有一个具有以下结构的 Spring Boot 应用程序:

  • com.test (Root Class) com.test(根类)
  • com.test.jpa (JPA Entities and Repositories) com.test.jpa(JPA 实体和存储库)
  • com.test.netty (netty TCP server) com.test.netty (netty TCP 服务器)

The root class is:根类是:

@ComponentScan(basePackages = {"com.test"})
//@EnableJpaRepositories
//@EntityScan
public class MyApplication {
...

The Netty Server: 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!");
    }

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.问题是:Repository 没有注入 com.test.netty 类。 I use it in root class and in JUnit tests without any problem.我在根类和 JUnit 测试中使用它没有任何问题。 I added @Repository to the repository and also added repo packages in @EnableJPARepositories but nothing changed.我将 @Repository 添加到存储库中,并在 @EnableJPARepositories 中添加了 repo 包,但没有任何改变。

Any ideas?有任何想法吗?

Well, if you're creating an instance of ServiceHandler yourself rather than using the bean instance Spring creates for you, of course no dependency injection will be performed.好吧,如果您自己创建ServiceHandler的实例而不是使用 Spring 为您创建的 bean 实例,那么当然不会执行依赖注入。 You need to inject the ServiceHandler bean into ServerChannelInit as well as make ServerChannelInit a @Component itself:您需要将ServiceHandler bean 注入ServerChannelInit并使ServerChannelInit本身成为@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);
        
    }
    ...
}

and then inject ServerChannelInit into NettyServer :然后将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);
...
}

I just executed with the followings, just add @SpringBootApplication in your main class.我刚刚执行了以下操作,只需在主类中添加@SpringBootApplication Uncomment @Repository取消注释@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();

    }
}

It works!有用!

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring数据jpa存储库注入失败,在Spring启动时使用@Autowired - spring data jpa repository inject fails using @Autowired in spring boot @Autowired不会注入Spring Data JPA存储库-NullPointerException - @Autowired does not inject Spring Data JPA Repository - NullPointerException Spring @Autowired 存储库在 @Override Netty 方法中不起作用 - Spring @Autowired repository not working in @Override Netty method Spring 引导:如何注入存储库 - Spring Boot: How to inject a Repository Spring Boot @Autowired Jpa存储库返回Null - Spring Boot @Autowired Jpa repository returns Null Spring引导Autowired Service和Repository抛出nullpointerexception - Spring boot Autowired Service and Repository throwing nullpointerexception Spring Boot Autowired Mongo存储库不起作用 - Spring boot Autowired Mongo Repository not working 使用 @Repository 注释 Dao 类时,Spring Boot 2.1 和 Hibernate 5.3 SessionFactory 未自动装配 - Spring boot 2.1 and Hibernate 5.3 SessionFactory not Autowired when annotating the Dao classes with @Repository spring 引导如何使用 @Autowired 没有 @Component 注释和 xml 配置注入 ApplicationContext 和 JdbcTemplate 的实例? - How does spring boot inject the instance of ApplicationContext and JdbcTemplate using @Autowired without @Component annotation and xml configuration? Spring Boot:在某些类中,Autowired CRUDRepository为空 - Spring Boot: Autowired CRUDRepository null, in certain classes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM