Get the App
SLTechnology News&Howtos  ›  Development  › 

How to solve the problem that Autowired can not be injected into bean in Test class

Shulou Source: shulou.com Published: 2022-06-03 19:34:52 10月15日 Update

This article will explain in detail how to solve the problem that Autowired can not be used to inject bean into Test class. I think it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

You cannot use Autowired to inject bean in a Test class

I took a good look at the notes about Spring this afternoon.

Using the AutoWired annotation in the test class has never been able to get the Bean, and a null pointer exception has been reported when the method is called.

Using the getBean method of ApplicationContext, we can get the Bean again, which proves that our Bean annotation is valid, and the problem should be in AutoWired. I have tried using AutoWired in other classes and found that it works.

The problem should be in the Test class. After searching for a long time, I finally found the problem!

The test unit I use myself in the test class is @ RunWith (BlockJUnit4ClassRunner.class). The correct one is to use the test unit @ RunWith (SpringJUnit4ClassRunner.class) in Spring-test.

Everyone must be careful in writing the code. Otherwise more time will be wasted.

Use autowired injection prompt Could not autowire. Test in the package. No beans of 'xxx' type found.

Tried various methods on the Internet, and finally found out

Replace autowired annotations with Resource annotations perfectly

This is the end of this article on "how to solve the problem that Autowired can not be injected into bean in Test classes". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

Tags: Questions annotations tests methods articles units that is more good good-looking practical code content places pointers articles time knowledge lower levels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Shulou Information vpn NVidia MariaDB