[Solved]: Encapsulate those methods in the Controller layer that use the Mapper interface class methods (BeanCreationNotAllowedException&NullPointException)

Problem phenomenon:

Today, in the process of studying how to extract the Controller layer method, after calling the Controller layer interface in postman, a BeanCreationNotAllowedException error occurred;

Or the null pointer exception of NullPointException.


problem analysis:

1. After extracting the Controller layer method to the CollectUtil class, when calling it again, the following problems occur, and the display method is not statically reported :

After modifying the method to a static method, and then using postman to call the Controller layer interface, a NullPointException error occurred again :

By viewing the error message, it can be seen that it is because of the methods of the Mapper interface used in the tool class, and the Mapper class is an interface interface, and an instance must be created to call the method normally. In a static static environment, the Mapper interface does not have an instance object. , So when calling the method of the object, an error will be reported: NullPointException. Therefore, changing to static cannot solve the problem .

So how to use the method of the instance object?

It's actually very simple: don't call it with a class name!

把CollectUtil.collectTaskExecute(absolutePath);

Change to: collectUtil.collectTaskExecute(absolutePath);

At this time collectUtil is an object reference, so we can use the @Autowired annotation to annotate CollectUtil collectUtil:

2. BeanCreationNotAllowedException error:

After modifying according to 1., and then using postman to call the Controller layer interface, an error occurred : BeanCreationNotAllowedException

By viewing the error message and code, you can know:

The error was reported because there was a problem when the Spring container created the bean object.In the CollectUtil class, I added four attributes: the @Autowired annotation to the xxxMapper interface, which realized that Spring manages the creation of objects, but it ignores a problem:

By looking at the head of the class, I can see that I forgot to give this class to Spring for management, so I also need to add the annotation @Component to the CollectUtil class and give the class to the Spring container for management.


Solution:

Annotate the CollectU class @Component

Successful operation:

The Controller layer interface call was also successful.

Guess you like

Origin blog.csdn.net/weixin_42585386/article/details/109157051