註解 @Resource 和 @Autowire

@Autowire

  • 作用:可以對類成員變量,方法以及構造函數進行標註,讓spring完成bean自動裝配(spring通過依賴注入創建實例)的工作。
  • @Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    //java項目www.fhadmin.org
    public @interface Autowired {
    
    	/**
    	 * Declares whether the annotated dependency is required.
    	 * <p>Defaults to {@code true}.
    	 */
    	boolean required() default true;
    
    }
    

    使用:

  • //java項目www.fhadmin.org
    public class ConditionTitleServiceImpl implements IConditionTitleService {
     
     	//創建類的實例,無需new對象
        @Autowired
        private IDataResourceDao iDataResourceDao;
        
        //set方法使用
        private People people;
        @Autowired
        public void setPeople(People people){
    		this.people = people;
    	}
        
        //構造法方法的使用
        private People people;
        @Autowired
        public ConditionTitleServiceImpl(People people){
    		this.people = people;
    	}
    	……
    }
    

    @Resource

  • 作用:按照名字進行匹配,如果沒有找到同名bean,則按照類型進行匹配,最終實現讓spring完成bean自動裝配(spring通過依賴注入創建實例)的工作。
  • @Target({TYPE, FIELD, METHOD})
    @Retention(RUNTIME)
    @Repeatable(Resources.class)
    public @interface Resource {
      ……
    }
    

    使用

  • //java項目www.fhadmin.org
    public class ConditionTitleServiceImpl implements IConditionTitleService {
        @Resource
        private IConditionTitleDao iConditionTitleDao;
    	……
    }
    

     

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章