類注解
@component 標注類,泛指各種組件,類不屬于各種分類的時候,用它做標注。
@Service 標注類,聲明該類為業務層組件,用于處理業務邏輯
@Repositor 標注類,聲明該類為持久層的接口。使用后,在啟動主程序類上需要添加@MapperScan(“xxx.xxx.xxx.mapper”)注解
@Mapper 標注類,用在持久層的接口上,注解使用后相當于@Reponsitory加@MapperScan注解,會自動進行配置加載
@Configuration Spring3.0以上,聲明該類是一個配置類,可以使用@Configuration用于定義配置類,可替換xml配置文件。被注解的類內部包含有一個或多個被@Bean注解的方法。
@Aspect 標注類 聲明這個類是一個切面類
@Controller 標注類,聲明該類為Spring MVC controller處理器組件,用于創建處理http請求的對象。
@RestController 標注類,聲明該類為Rest風格控制器組件,該注解是Spring4之后加入的注解,用它替代@Controller就不需要再配置@ResponseBody,默認返回json格式
@RequestMapping:既可以注解在類上,也可以注解在類的方法上,該類提供初步的請求映射信息。注解在類上是相對于 Web 根目錄,注解在方法上的是相對于類上的路徑
1
2
3
4
5
6
7
|
@Controller @RequestMapping ( "/user" ) public class UserController { @RequestMapping ( "/login" ) public String login() { return "success" ; } |
此時,調用時使用:http://IP地址:端口號/網站根路徑/user/login
方法或屬性上注解
@Autowired 用來裝配bean,可以寫在字段或者方法上。默認情況下必須要求依賴對象必須存在,如果要允許null值,可以設置它的required屬性為false,如:@Autowired(required=false)
@Qualifier 如果一個接口有兩個或者兩個以上的實現類,就要使用到@Qualifier注解,qualifier的英文含義是合格者的意思,通過此注解,標注那個實現類才是這次要用到的實現類。如:
1
2
3
4
5
6
7
8
9
10
11
12
|
@Service ( "service" ) public class EmployeeServiceImpl implements EmployeeService { public EmployeeDto getEmployeeById(Long id) { return new EmployeeDto(); } } @Service ( "service1" ) public class EmployeeServiceImpl1 implements EmployeeService { public EmployeeDto getEmployeeById(Long id) { return new EmployeeDto(); } } |
service和service1同時實現接口EmployeeService,@Autowired注入時,通過@Qualifier告訴spring,要哪一個實現類,代碼如下
1
2
3
|
@Autowired @Qualifier ( "service" ) EmployeeService employeeService; |
此處是service,而不是service1。
@Bean 與@Configuration標注類配合使用,等同于xml文件配置的bean。如:
1
2
3
4
|
< bean id = "user" class = "com.zhang.bean.User" > < property name = "userName" value = "zhangsan" ></ property > < property name = "age" value = "26" ></ property > </ bean > |
等同于
1
2
3
4
5
6
7
|
@Bean public User getUser(){ User user = new User(); user.setUserName( "zhangsan" ), user.setAge( 26 ), return user; } |
@After、@Before、@Around:與@Aspect配合使用,直接將切點作為參數,在方法執行之后執行、之前執行及之前和之后均執行。
@RequestBody:可用在方法上,也可以用在參數上。注解在方法上,代表用戶返回json數據,而不是頁面。
參數注解
@RequestBody:注解在方法的參數上,代表接收的參數是來自requestBody中,即請求體。用于處理非 Content-Type: application/x-www-form-urlencoded編碼格式的數據,如:application/json、application/xml等類型的數據,使用注解@RequestBody可以將body里面所有的json數據傳到后端,后端再進行解析
@RequestParam:使用在方法參數參數上,接收的參數是來自HTTP請求體或請求url的QueryString中。可以接受簡單類型的屬性,也可以接受對象類型。@RequestParam用來處理 Content-Type 為 application/x-www-form-urlencoded 編碼的內容,Content-Type默認為該屬性。
@PathVariable: 使用在方法參數參數上。當@RequestMapping URI template 樣式映射時, paramId可通過 @Pathvariable注解綁定它傳過來的值到方法的參數上,如:
1
2
3
4
5
6
7
8
|
@Controller @RequestMapping ( "/user/{Id}" ) public class DemoController { @RequestMapping ( "/pets/{petId}" ) public void queryPetByParam( @PathVariable String Id, @PathVariable String petId) { // implementation } } |
以上就是Spring框架學習常用注解匯總的詳細內容,更多關于Spring框架注解的資料請關注服務器之家其它相關文章!
原文鏈接:https://blog.csdn.net/guoyp2126/article/details/110221840