Remember a weird null pointer

I received a question saying that occasionally there will be a null pointer after the service is started. Occasional.

background

The project is a SpringBoot project,

According to the error, the service injection is null, and then the pointer is null during execution.

@Service("xxxService")
public class xxxService {

    @Autowired
    AService aService;


    public void exec(){
        aService.run();//这里抛了空指针
    }
}

Problem representation

Occasionally null pointers are sometimes ok and sometimes null pointers after the service is started.

Troubleshoot

The first thing that comes to mind is that the startup is abnormal. Spring Bean initialization failed.

Log on to the server and check the startup log if the startup is abnormal. There is no exception.

But it is obvious to see another problem.

When the service starts. Spring Bean was instantiated twice.

The problem was immediately apparent.

problem

Viewed the main method.

public class SpringMain{
    public static void main(String[] args){
        //.....略过中间逻辑

        application.run();
        //......略过中间逻辑
        application.run();
    }
}

Obviously the program has run twice. The bean is instantiated twice.

So why does Spring not instantiate the bean for the second time? ? Is the second instantiated bean null?

the reason

This is the process of Spring initialization.

There are two runs here, but the same Spring container is run, and Bean is loaded in the same Spring container.

But it will judge whether the Bean has been initialized. If it has been initialized, it will not be initialized.

solve

Remove a run ()

to sum up

Novices still have to understand more principles. Writing code will write, but positioning problems is also very important,

The two instantiations performed so obviously are invisible. . .

Guess you like

Origin www.cnblogs.com/ElEGenT/p/12708742.html