Spring中的Spring JSR-250 注释之@Resource

时间:2022-07-22
本文章向大家介绍Spring中的Spring JSR-250 注释之@Resource,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

@Resource注解相当于By Name装配方式。

TextEditor:

package com.sap;

import javax.annotation.Resource;
public class TextEditor {
   private SpellChecker spellChecker;
   @Resource(name= "spellChecker223")
   public void setSpellChecker( SpellChecker spellChecker ){
      this.spellChecker = spellChecker;
   }
   public SpellChecker getSpellChecker(){
      return spellChecker;
   }
   public void spellCheck(){
      spellChecker.checkSpelling();
   }
}

意思是,需要在Beans.xml里寻找一个id 为spellChecker223的bean:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:annotation-config/>

   <!-- Definition for textEditor bean without constructor-arg  -->
   <bean id="textEditor" class="com.sap.TextEditor">
   </bean>

   <!-- Definition for spellChecker bean -->
   <bean id="spellChecker223" class="com.sap.SpellChecker">
   </bean>

</beans>

这里的id必须和TextEditor.java里@Resource name属性指定的一致。