spring4.x注解概述
1. 背景
注解可以減少代碼的開(kāi)發(fā)量,spring提供了豐富的注解功能,因項(xiàng)目中用到不少注解,因此下定決心,經(jīng)spring4.x中涉及到的注解羅列出來(lái),供查詢使用。
2. spring注解圖
? ? 2.1 spring-context模塊的注解圖
?2.2 spring-web注解
2.3 spring其它模塊的注解
3. 注解實(shí)例說(shuō)明
本來(lái)準(zhǔn)備寫(xiě)一些demo來(lái)介紹常用的注解用法,但網(wǎng)上搜索了一些,發(fā)現(xiàn)有類(lèi)似的了,就直接整理后引用了。
4 附錄:(為了讓讀者不用翻頁(yè),我直接copy過(guò)來(lái)了,并進(jìn)行了適當(dāng)?shù)呐虐?#xff0c;若涉及到版權(quán)問(wèn)題,請(qǐng)告知,我將刪除之)
原文鏈接:http://wenku.baidu.com/link?url=zo6gMapARIdb4SMsYbtMOqLpwF2y9jUJW1T6CF_7fIDh6Q1Y7k_Ox3pVPvLd1Cn3DukwrMTO8RNA5cJjCSCWS5VZUsutbsftXn8epXV65SS
Spring2.5?注解介紹(3.0通用)
Auther:?韓群峰?Version:?1.0.0?Date:?2011-03-15
??注解說(shuō)明
??注冊(cè)注解處理器
??方式一:bean
<bean class="org.springframework.beans.factory.annotation.
AutowiredAnnotationBeanPostProcessor"/>
??方式二:?命名空間<context:annotation-config />
<context:annotationconfig />?將隱式地向Spring?容器注冊(cè)AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor?、?PersistenceAnnotationBeanPostProcessor?以及RequiredAnnotationBeanPostProcessor?這4?個(gè)BeanPostProcessor?。
??方式三:?命名空間<context:component-scan />
如果要使注解工作,則必須配置component-scan?,實(shí)際上不需要再配置annotation-config。
base-package?屬性指定了需要掃描的類(lèi)包,類(lèi)包及其遞歸子包中所有的類(lèi)都會(huì)被處理。還允許定義過(guò)濾器將基包下的某些類(lèi)納入或排除。
?
?
??Spring?支持以下4?種類(lèi)型的過(guò)濾方式:
????????????????注解?org.example.SomeAnnotation?將所有使用SomeAnnotation?注解的類(lèi)過(guò)濾出來(lái)
????????????????類(lèi)名指定?org.example.SomeClass?過(guò)濾指定的類(lèi)
????????????????正則表達(dá)式?com.kedacom.spring.annotation.web..*?通過(guò)正則表達(dá)式過(guò)濾一些類(lèi)
????????????????AspectJ?表達(dá)式?org.example..*Service+?通過(guò)AspectJ?表達(dá)式過(guò)濾一些類(lèi)
?
?
??正則表達(dá)式的過(guò)濾方式舉例:
<context:component-scanbase-package="com.casheen.spring.annotation">
<context:exclude-filtertype="regex"
expression="com.casheen.spring.annotation.web..*"/>
</context:component-scan>
??注解的過(guò)濾方式舉例:
<context:component-scan base-package="com.netqin" >
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Service"/>
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
?
啟用Spring MVC?注解
??啟動(dòng)Spring MVC?的注解功能,完成請(qǐng)求和注解POJO?的映射
??<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
注解舉例:
@Controller
? ? ? ???例如
? ? ? ? ? @Controller
? ? ? ? ? ?public class SoftCreateController extends SimpleBaseController {}
? ? ? ???或者
? ? ? ? ?@Controller("softCreateController")
? ? ? ???說(shuō)明
? ? ? ? ? @Controller?負(fù)責(zé)注冊(cè)一個(gè)bean?到spring?上下文中,bean?的ID?默認(rèn)為類(lèi)名稱開(kāi)頭字母小寫(xiě)
?
@Service
? ? ? ??例如
? ? ? ?@Service
? ? ? ? public class SoftCreateServiceImpl implements ISoftCreateService {}
? ? ? ??或者
? ? ? ? @Service("softCreateServiceImpl")
? ? ? ??說(shuō)明
? ? ? ? ?@Service?負(fù)責(zé)注冊(cè)一個(gè)bean?到spring?上下文中,bean?的ID?默認(rèn)為類(lèi)名稱開(kāi)頭字母小寫(xiě)
?
@Autowired
? ? ? ??例如
? ? ? ? ?@Autowired
? ? ? ? ? private ISoftPMService softPMService;
? ? ? ???或者
? ? ?@Autowired(required=false)
???? private ISoftPMService softPMService = new SoftPMServiceImpl();
? ? ? ??說(shuō)明
? ? @Autowired?根據(jù)bean?類(lèi)型從spring?上線文中進(jìn)行查找,注冊(cè)類(lèi)型必須唯一,否則報(bào)異常。與@Resource?的區(qū)別在于,@Resource?允許通過(guò)bean?名稱或bean?類(lèi)型兩種方式進(jìn)行查找@Autowired(required=false)?表示,如果spring?上下文中沒(méi)有找到該類(lèi)型的bean?時(shí), 才會(huì)使用new SoftPMServiceImpl();
@Autowired 標(biāo)注作用于 Map 類(lèi)型時(shí),如果 Map 的 key 為 String 類(lèi)型,則 Spring 會(huì)將容器中所有類(lèi)型符合 Map 的 value 對(duì)應(yīng)的類(lèi)型的 Bean 增加進(jìn)來(lái),用 Bean 的 id 或 name 作為 Map 的 key。
@Autowired 還有一個(gè)作用就是,如果將其標(biāo)注在 BeanFactory 類(lèi)型、ApplicationContext 類(lèi)型、ResourceLoader 類(lèi)型、ApplicationEventPublisher 類(lèi)型、MessageSource 類(lèi)型上,那么 Spring 會(huì)自動(dòng)注入這些實(shí)現(xiàn)類(lèi)的實(shí)例,不需要額外的操作。?
?
@RequestMapping
? ? ??類(lèi)
@Controller?
@RequestMapping("/bbtForum.do")
public class BbtForumController {
???????????? @RequestMapping(params = "method=listBoardTopic")
public String listBoardTopic(int topicId,User user) {}
}
? ???方法
??????????????@RequestMapping("/softpg/downSoftPg.do")
?? ? ? ? ? ?? @RequestMapping(value="/softpg/ajaxLoadSoftId.do",method = POST)
????????????? @RequestMapping(value = "/osu/product/detail.do", params = { "modify=false" }, method =POST)
????說(shuō)明
??? @RequestMapping?可以聲明到類(lèi)或方法上
? ??參數(shù)綁定說(shuō)明
如果我們使用以下的?URL?請(qǐng)求:
http://localhost/bbtForum.do?method=listBoardTopic&topicId=1&userId=10&userName=tom
topicId URL?參數(shù)將綁定到?topicId?入?yún)⑸?#xff0c;而?userId?和?userName URL?參數(shù)將綁定到?user?對(duì)象的?userId?和?userName?屬性中。和?URL?請(qǐng)求中不允許沒(méi)有?topicId?參數(shù)不同,雖然?User?的?userId?屬性的類(lèi)型是基本數(shù)據(jù)類(lèi)型,但如果?URL?中不存在?userId?參數(shù),Spring?也不會(huì)報(bào)錯(cuò),此時(shí)?user.userId?值為?0?。如果?User?對(duì)象擁有一 個(gè)?dept.deptId?的級(jí)聯(lián)屬性,那么它將和?dept.deptId URL?參數(shù)綁定。
?
@RequestParam
???參數(shù)綁定說(shuō)明
@RequestParam("id")
http://localhost/bbtForum.do?method=listBoardTopic&id=1&userId=10&userName=tom
listBoardTopic(@RequestParam("id")int topicId,User user)?中的?topicId?綁定到?id?這個(gè)?URL?參數(shù), 那么可以通過(guò)對(duì)入?yún)⑹褂?@RequestParam?注解來(lái)達(dá)到目的
@RequestParam(required=false):參數(shù)不是必須的,默認(rèn)為true
@RequestParam(value="id",required=false)
請(qǐng)求處理方法入?yún)⒌目蛇x類(lèi)型
????????????????Java?基本數(shù)據(jù)類(lèi)型和?String
????????????????????默認(rèn)情況下將按名稱匹配的方式綁定到?URL?參數(shù)上,可以通過(guò)?@RequestParam?注解改變默認(rèn)的綁定規(guī)則
????????????????request/response/session
? 既可以是?Servlet API?的也可以是?Portlet API?對(duì)應(yīng)的對(duì)象,Spring?會(huì)將它們綁定到Servlet?和?Portlet?容器的相應(yīng)對(duì)象上
? ??org.springframework.web.context.request.WebRequest
?內(nèi)部包含了?request?對(duì)象
? ??java.util.Locale
綁定到?request?對(duì)應(yīng)的?Locale?對(duì)象上
??????????java.io.InputStream/java.io.Reader
? ? ? ? ? ?可以借此訪問(wèn)?request?的內(nèi)容
??????????java.io.OutputStream / java.io.Writer
可以借此操作?response?的內(nèi)容
???????????任何標(biāo)注了?@RequestParam?注解的入?yún)?/p>
? ? ? ? ? ? 被標(biāo)注?@RequestParam?注解的入?yún)⒔壎ǖ教囟ǖ?request?參數(shù)上。
???????????java.util.Map / org.springframework.ui.ModelMap
它綁定?Spring MVC?框架中每個(gè)請(qǐng)求所創(chuàng)建的潛在的模型對(duì)象,它們可以被?Web?視圖對(duì)象訪問(wèn)(如?JSP?)
???????????命令/?表單對(duì)象(注:一般稱綁定使用?HTTP GET?發(fā)送的?URL?參數(shù)的對(duì)象為命令對(duì)象,而稱綁定使用HTTP POST?發(fā)送的?URL?參數(shù)的對(duì)象為表單對(duì)象)
? ? ? ? ? ? 它們的屬性將以名稱匹配的規(guī)則綁定到?URL?參數(shù)上,同時(shí)完成類(lèi)型的轉(zhuǎn)換。
? ? ? ? ? ? 而類(lèi)型轉(zhuǎn)換的規(guī)則可以通過(guò)?@InitBinder?注解或通過(guò)?HandlerAdapter?的配置進(jìn)行調(diào)?整
?????org.springframework.validation.Errors / org.springframework.validation.BindingResult
? ? ? ? ? ? 為屬性列表中的命令/?表單對(duì)象的校驗(yàn)結(jié)果,注意檢驗(yàn)結(jié)果參數(shù)必須緊跟在命令/?表單對(duì)象的后面
??????org.springframework.web.bind.support.SessionStatus
?可以通過(guò)該類(lèi)型?status?對(duì)象顯式結(jié)束表單的處理,這相當(dāng)于觸發(fā)?session?清除其中的通過(guò)@SessionAttributes?定義的屬性
請(qǐng)求處理方法返回值的可選類(lèi)型
? ??void
此時(shí)邏輯視圖名由請(qǐng)求處理方法對(duì)應(yīng)的?URL?確定,如以下的方法:
@RequestMapping("/welcome.do")
public void welcomeHandler() {}
對(duì)應(yīng)的邏輯視圖名為?“?welcome?”?
? ??String
此時(shí)邏輯視圖名為返回的字符,如以下的方法:
@RequestMapping(method = RequestMethod.GET)
public String setupForm(@RequestParam("ownerId") int ownerId, ModelMap model) {
Owner owner = this.clinic.loadOwner(ownerId);
model.addAttribute(owner);
return "ownerForm";
}
對(duì)應(yīng)的邏輯視圖名為?“?ownerForm?”?
??org.springframework.ui.ModelMap
和返回類(lèi)型為?void?一樣,邏輯視圖名取決于對(duì)應(yīng)請(qǐng)求的?URL?,如下面的例子:
@RequestMapping("/vets.do")
public ModelMap vetsHandler() {
return new ModelMap(this.clinic.getVets());
}
對(duì)應(yīng)的邏輯視圖名為?“?vets?”?,返回的?ModelMap?將被作為請(qǐng)求對(duì)應(yīng)的模型對(duì)象,可以在?JSP?視圖頁(yè)面中訪問(wèn)到。
??ModelAndView
當(dāng)然還可以是傳統(tǒng)的?ModelAndView?。
?
@ModelAttribute
? ? ? ? ???作用域:request
? ? ? ? ???例如
? ? ? ? ? ?? @RequestMapping("/base/userManageCooper/init.do")
? ? ? ? ?? ? public String handleInit(@ModelAttribute("queryBean") ManagedUser sUser,Model model,){
? ? ? ? ? ??或者
??????????????@ModelAttribute("coopMap")//?將coopMap?返回到頁(yè)?面
????? ? ???public Map<Long,CooperatorInfo> coopMapItems(){}
? ? ? ? ? ??說(shuō)明
@ModelAttribute?聲明在屬性上,表示該屬性的value?來(lái)源于model?里"queryBean"?,并被保存到model?里@ModelAttribute聲明在方法上,表示該方法的返回值被保存到model?里
?
@Cacheable?和@CacheFlush
????????????????@Cacheable?:聲明一個(gè)方法的返回值應(yīng)該被緩存。例如:@Cacheable(modelId = "testCaching")
????????????????@CacheFlush?:聲明一個(gè)方法是清空緩存的觸發(fā)器。例如:@CacheFlush(modelId = "testCaching")
????????????????說(shuō)明
?????????????? 要配合緩存處理器使用,參考:?http://hanqunfeng.iteye.com/blog/603719
spring3.0沒(méi)有對(duì)緩存提供支持,不過(guò)3.1之后就有了,可以參考:Spring3.1 Cache注解
?
@Resource
? ? ? ??例如
??????????????@Resource
? ? ? ? ? ??? private DataSource dataSource; // inject the bean named 'dataSource'
? ? ? ??或者
@Resource(name="dataSource")
@Resource(type=DataSource.class)
??說(shuō)明
@Resource?默認(rèn)按bean?的name?進(jìn)行查找,如果沒(méi)有找到會(huì)按type?進(jìn)行查找,
此時(shí)與@Autowired?類(lèi)?似
在沒(méi)有為 @Resource 注解顯式指定 name 屬性的前提下,如果將其標(biāo)注在 BeanFactory 類(lèi)型、ApplicationContext 類(lèi)型、ResourceLoader 類(lèi)型、 ApplicationEventPublisher 類(lèi)型、MessageSource 類(lèi)型上,那么 Spring 會(huì)自動(dòng)注入這些實(shí)現(xiàn)類(lèi)的實(shí)例,不需要額外的操作。此時(shí) name 屬性不需要指定 ( 或者指定為""),否則注入失敗;
?
@PostConstruct?和@PreDestroy
??@PostConstruct
在方法上加上注解@PostConstruct?,這個(gè)方法就會(huì)在Bean?初始化之后被Spring?容器執(zhí)?行
(注:Bean?初始化包括,實(shí)例化Bean?,并裝配Bean?的屬性(依賴注入))。
?
??@PreDestroy
在方法上加上注解@PreDestroy?,這個(gè)方法就會(huì)在Bean?被銷(xiāo)毀前被Spring?容器執(zhí)行。
?
@Repository
??與@Controller?、@Service?類(lèi)似,都是向spring?上下文中注冊(cè)bean?,不在贅述。
?
@Component?(不推薦使用)
??@Component
@Component?是所有受Spring?管理組件的通用形式,Spring?還提供了更加細(xì)化的注解形式:? @Repository?、@Service、@Controller?,它們分別對(duì)應(yīng)存儲(chǔ)層Bean?,業(yè)務(wù)層Bean?,和展示層Bean?。
目前版本(2.5?)中,這些注解與@Component?的語(yǔ)義是一樣的,完全通用,?在Spring?以后的版本中可能會(huì)給它們追加更多的語(yǔ)義。?所以,我們推薦使用@Repository?、@Service?、@Controller?來(lái)替代@Component?。
?
@Scope
? ? ? ???例如
? ? ? ? ? ? ?@Scope("session")
? ? ? ? ? ? ?@Repository()
? ? ? ? ? ? ? public class UserSessionBean implementsSerializable {}
? ? ? ???說(shuō)明
在使用XML?定義Bean?時(shí),可以通過(guò)bean?的scope?屬性來(lái)定義一個(gè)Bean?的作用范圍,
同樣可以通過(guò)@Scope?注解來(lái)完成
???????@Scope中可以指定如下值:
?????? singleton:定義bean的范圍為每個(gè)spring容器一個(gè)實(shí)例(默認(rèn)值)
?????? prototype:定義bean可以被多次實(shí)例化(使用一次就創(chuàng)建一次)
?????? request:定義bean的范圍是http請(qǐng)求(springMVC中有效)
?????? session:定義bean的范圍是http會(huì)話(springMVC中有效)
?????? global-session:定義bean的范圍是全局http會(huì)話(portlet中有效)
?
@SessionAttributes
??說(shuō)明
Spring?允許我們有選擇地指定?ModelMap?中的哪些屬性需要轉(zhuǎn)存到?session?中,
以便下一個(gè)請(qǐng)求屬對(duì)應(yīng)的?ModelMap?的屬性列表中還能訪問(wèn)到這些屬性。
這一功能是通過(guò)類(lèi)定義處標(biāo)注?@SessionAttributes?注解來(lái)實(shí)現(xiàn)的。
@SessionAttributes?只能聲明在類(lèi)上,而不能聲明在方法上。
??例如
@SessionAttributes("currUser") //?將ModelMap?中屬性名為currUser?的屬性
@SessionAttributes({"attr1","attr2"})
@SessionAttributes(types = User.class)
@SessionAttributes(types = {User.class,Dept.class})
@SessionAttributes(types = {User.class,Dept.class},value={"attr1","attr2"})
?
@InitBinder
??說(shuō)明
如果希望某個(gè)屬性編輯器僅作用于特定的?Controller?,
可以在?Controller?中定義一個(gè)標(biāo)注?@InitBinder?注解的方法,
可以在該方法中向?Controller?了注冊(cè)若干個(gè)屬性編輯器
??例如
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
?
@Required
? ? ? ??例如
??????????????@required??????????????
??????????????public? setName(String name){}?
? ? ? ???說(shuō)明
??????????????@?required?負(fù)責(zé)檢查一個(gè)bean在初始化時(shí)其聲明的?set方法是否被執(zhí)行,?當(dāng)某個(gè)被標(biāo)注了 @Required 的 Setter 方法沒(méi)有被調(diào)用,則 Spring 在解析的時(shí)候會(huì)拋出異常,以提醒開(kāi)發(fā)者對(duì)相應(yīng)屬性進(jìn)行設(shè)置。 @Required 注解只能標(biāo)注在 Setter 方法之上。因?yàn)橐蕾囎⑷氲谋举|(zhì)是檢查 Setter 方法是否被調(diào)用了,而不是真的去檢查屬性是否賦值了以及賦了什么樣的值。如果將該注解標(biāo)注在非 setXxxx() 類(lèi)型的方法則被忽略。
?
@Qualifier
? ? ? ???例如
??????????????@Autowired
????????????? @Qualifier("softService")
????????????? private ISoftPMService softPMService;
? ? ? ???說(shuō)明
??????????? 使用@Autowired?時(shí),如果找到多個(gè)同一類(lèi)型的bean,則會(huì)拋異常,此時(shí)可以使用?@Qualifier("beanName"),明確指定bean的名稱進(jìn)行注入,此時(shí)與?@Resource指定name屬性作用相同。
轉(zhuǎn)載于:https://www.cnblogs.com/davidwang456/p/4432410.html
總結(jié)
以上是生活随笔為你收集整理的spring4.x注解概述的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Spring 3.1 Environme
- 下一篇: Understanding Spring