Introduce @Resource annotation report empty pointer
I just started learning the Spring framework recently. When using the annotation @Resource, no matter how I apply it, I will report a null pointer. The main reason is that the JDK version does not support it.
Solution
1. Introduce dependencies in maven configuration file
tomcat-annotations-api 9.0.13
2. Replace the local JDK version, preferably above 1.8. Note that the 1.9 JDK version does not support it, and there are bugs.
The spring project cannot introduce @Resource annotation
question
When introducing @Resource annotation in spring project, there is a red underscore error, and automatic code completion cannot occur when entering annotation.
Solution
Missing dependencies for packages in Spring projects. Add dependencies to the maven configuration file.
<!-- /artifact//-api --> <dependency> <groupId></groupId> <artifactId>-api</artifactId> <version>1.2</version> </dependency>
1. Import namespace in spring configuration file
xmlns:context="/schema/context" /schema/context /schema/context/spring-context-2.
2. Introduce annotation parser
context:annotation-config></context:annotation-config>
3. Introduce beans in spring configuration file
4. Add to the properties of a class
@Resource(name="student_annotation") private Student student;
From the annotation itself
@Target({TYPE, FIELD, METHOD}) @Retention(RUNTIME) public @interface Resource { String name() default ""; }
This annotation can be used on attributes or methods, but is generally used on attributes
This annotation has a property name, the default value is ""
5. Analyze the entire process
- 1. When starting the spring container, the spring container loads the configuration file
- 2. In the spring configuration file, as long as the configuration of the bean is encountered, an object will be created for the bean.
- 3. Find all beans within the scope included in the spring container, and see which beans have @Resource added to the properties or methods.
- 4. After finding the @Resource annotation, determine whether the attribute of the annotation name is "" (name is not written)
If the name attribute is not written, the value of the attribute name will be matched with the value of the ID in spring. If the match is successful, the value will be assigned.
If the match is not successful, the match will be performed according to the type. If the match is not successful, an error will be reported.
If there is a name attribute, it will match the value of the name attribute and the ID in the spring bean. If the match is successful, the assignment will be made. If it fails, an error will be reported.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.