The first thing to note is that although both @Resource and @autowire are used for dependency injection annotation, there are differences.
1 resource does not depend on spring, the latter is the opposite, so as far as possible to reduce, use resource;
2 Resource is preferred to match by variable name, and @resource (name= "") can also be used to specify the variable name to inject. Autowire is preferred by type, with @qualifier can also specify variable name.
3 There is no supernatural event! There is no supernatural event! There is no supernatural event! The important thing to say three times. If there is a nullpointerexception, it must be the code is wrong.
When the injected variable is called, the NPE is thrown, which is followed by the following experience:
Whether the 0 spring XML configuration files are included in Classpath (resources, WebApp, or even Java), if there are multiple XML files, the include hierarchy is correct.
1 Determines whether the package containing the class is scanned by spring. Check the configuration file for:
</> <base-package= "me.xxx"/> <base-package= "me.yyy"/>
2 Check if the bean has a duplicate definition.
3 Check whether the injected dependency has setter methods. Spring relies on the setter method of the variable when it injects dependencies on us, and without any hint of injection failure if it is missing.
@ResourceClassType ClassType; Public Setclasstype (ClassType ClassType) { this. ClassType = ClassType;}
4 for a static dependency, add @resource on its setter method to deceive spring into a static variable.
Static ClassType ClassType; @Resource Public Setclasstype (ClassType ClassType) { this. ClassType = ClassType;}
5 If the NPE is present when using @resource in a test case, consider whether the bean is not created in ApplicationContext at all.
You can write test cases in the following ways to avoid initializing a large number of fields (requires JUnit 4.9 or more):
@RunWith (Springjunit4classrunner.class) @ContextConfiguration (Locations= {"Classpath:/spring-xxx.xml"}) Public classBasetestextendsabstractjunit4springcontexttests {@BeforeClass Public Static voidSetupbeforeclass ()throwsException {//add whatever. }} Public classXxxxtestextendsBasetest {...}
Of course, if you know exactly what context a single test case needs to use, you can write the paragraph in the test case xxxtest itself, avoiding loading the entire context each time, leading to a heavyweight use case.
6 If you want to check whether the context is created properly, or if a bean is in context, you can directly use @resource to bring up the global context named "ApplicationContext".
How to troubleshoot NPE when "Java" uses @reource or @autowire dependency Injection