A detailed explanation of the java javax.annotation.Resource annotation

  • 2020-05-12 02:34:08
  • OfStack

java note: java javax.annotation.Resource

When we inject objects into the class configuration in xml, we find that the xml file becomes more and more bloated and difficult to maintain. At this point we can use the annotation mechanism to configure the injection object for the class.

Java provides us with the annotation javax.annotation.Resource.

spring framework provides org. springframework. beans. factory. annotation. Autowired.

1 normally we use the javax.annotation.Resource annotation, because then we can implement the de-coupling with the spring framework.

@Resource can be applied to fields and functions. As for the field, if we just simply write it like this

@Resource
PersonDao p;

At this point, the injection process of spring into p is 1: first, find whether there is an element in xml with id as p

2: if not, see if there is an name property (@Resource name= "") and if there is, look for name

3: otherwise look for elements of type persondao

@Resource operates on the set function.

Such as:


@Resource
  public void setP(PersonDao p) {
 this.p = p;
  }

The @Autowired annotation looks for elements by type, such as PersonDao p, which looks for elements of type PersonDao in the xml file

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: