Spring 框架 spring註解的引入和使用

2021-09-28 17:33:09 字數 2426 閱讀 1815

xmlns:context="                

/spring-context.xsd"          

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

必須:註解配置引入

該配置隱式引入了spring註解處理器bean:

autowiredannotationbeanpostprocessor          自動裝配

commonannotationbeanpostprocessor            共同註解

requiredannotationbeanpostprocessor            申明註解

使用註解是為了簡化開發,每次都要配置比較繁瑣,常用註解有:

@autowired:自動裝配註解

@repository:主要針對dao類

@service:針對service實現類

@controller:針對控制器實現類註解

@component:通過註解,針對實體類

@webservlet:用於指定servlet訪問路勁

@primary:設定自動裝配優先裝配註解

@required:是否必須註解

@scope:用於定受管bean的作用域,單例(預設)、多例項等

**:

package com.spring.annotationdi;

import org.springframework.stereotype.repository;

/** * @classname: student

**/@repository

public class student

}

配置:

不過需要手動指定掃瞄包:

測試:

package com.spring.annotationdi;

/** *

* @classname: test

* @description: todo

**/public class test

}

結果:

@autowired:用於自動裝配,**型別 bytype

@resource:基於名稱的自動裝配 byname(建議使用)

**:

package com.spring.annotationdi;

import org.springframework.beans.factory.annotation.autowired;

import org.springframework.stereotype.service;

/** * @classname: studentservice

* @description: todo

**/@service

public class studentservice

}

package com.spring.annotationdi;

import org.springframework.stereotype.repository;

/** * @classname: student

**/@repository

public class studentdao

}

測試:

package com.spring.annotationdi;

/** *

* @classname: test

* @description: todo

**/public class test

}

結果:

問題:@autowired是通過bytype來注入,如果出現同型別問題會報錯

解決辦法:

@qualifier指定要裝配bean的id

在bean中指定primary屬性,指定優先裝備物件

在受管bean中加上@primary註解,指定優先裝備物件

spring框架下的 Qualifier註解

autowired是根據型別進行自動裝配的。如果當spring上下文中存在不止乙個userdao型別的bean時,就會丟擲beancreationexception異常 如果spring上下文中不存在userdao型別的bean,也會丟擲beancreationexception異常。我們可以使用 ...

Spring中Responsebody註解的作用

好長一段時間以來都只是寫些測試 好久沒寫專案 了,以至於spring那套東西日漸生疏了。最近在折騰乙個小專案,寫了乙個controller用來響應ajax請求,結果斷點除錯發現一直返回 404 not response.折騰了快2小時,一直沒想到是註解的問題,萬般無賴之下上了度娘,方才如夢初醒,特意...

spring學習筆記(7) spring常用註解

1 引入context命名空間 在spring的配置檔案中 配置檔案如下 xml 收藏 xmlns context org schema context org schema context spring context 2.5 xsd開啟配置 spring 會自動掃瞄cn.pic包下面有註解的類,...