I also encountered bean injection failure before, but it didn’t seem to take it seriously. I quickly locked the cause, but recently I received a task requiring me to use a Netty to receive data started by a device and parse it. I used SpringBoot and Netty integration for personal use Injecting the Service layer into NettyHandle has been impossible

Describe the problem:

Normal injection beans are injectable, and there are three common problems with not being able to inject

1. Not loaded (not scanned)

In a SpringBoot project, this is almost certainly not the case (class Bean annotations will be scanned under any subpackage of the SpringBoot boot class).

2. The object is not injected correctly

This usually happens when you inject static objects and the solution is very simple to use methods to set properties into properties

private static LighterServer lighterServer;
@Autowired
private void setLighterServer(LighterServer lighterServer) {
 NettyApplication.lighterServer = lighterServer;
}
Copy the code

 

3. Dependency injection has the problem of new keyword new object

I’ve always known this but this is the first time I’ve used Netty and I forgot about this

For example, when using Netty, the New keyword is often used when initializing the service from the creation of the object so that the subsequent nested Bean cannot be loaded and injected properly. Therefore, it is always null

3.1 OK Know the reason then to solve it

The first thing we need to know is how is it created to inject a class with a null property (New or injection)

And then I’m going to change it and notice where it’s circled in red

 

This article is mainly about Netty, because many Netty examples on the web use the New keyword when initializing the service, whether it is the injection initializer or the injection Handel

The springBoot project is executed after the bean is loaded. The following is the printout of the same object