一直想吧常用的Spring註解整理,並配合樣例進行說明,今天終於有機會
註冊註解處理器:
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<context:component-scan />
要使註解工作,必須配置這個,以下是我寫的樣例<!-- 自動掃描該包,使SpringMVC認爲包下用了@controller註解的類是控制器 -->
<context:component-scan base-package="com.iboy.controller" />
以下是網友的舉例:Spring 支持以下 4 種類型的過濾方式:
• 註解 org.example.SomeAnnotation 將所有使用 SomeAnnotation 註解的類過濾出來
• 類名指定 org.example.SomeClass 過濾指定的類
• 正則表達式 com.kedacom.spring.annotation.web..* 通過正則表達式過濾一些類
• AspectJ 表達式 org.example..*Service+ 通過 AspectJ 表達式過濾一些類
• 正則表達式的過濾方式舉例:
<context:component-scanbase-package="com.casheen.spring.annotation">
<context:exclude-filtertype="regex"
expression="com.casheen.spring.annotation.web..*"/>
</context:component-scan>
• 註解的過濾方式舉例:
<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 註解
@Controller
@Controller
public class iboyController {}
• 或者
@Controller("iboyControllerr") //可以自定義Controller名稱
• 說明
@Controller 負責註冊一個 bean 到 spring 上下文中,bean 的 ID 默認爲類名稱開頭字母小寫
@Service
@Service
public class iboyServiceImpl implements ISoftCreateService {}
• 或者
@Service("iboyServiceImpl")//可以自定義Servicer名稱
• 說明
@Service 負責註冊一個 bean 到 spring 上下文中,bean 的 ID 默認爲類名稱開頭字母小寫
@Autowired
@Autowired
private IboyService softPMService;
• 或者
@Autowired(required=false) //這個在下面說明,默認是true
private IboyService iboyService = new IboyServiceImp ();
@Autowired 根據 bean 類型從 spring 上線文中進行查找,註冊類型必須唯一,否則報異常。與@Resource 的區別在於,@Resource 允許通過 bean 名稱或 bean 類型兩種方式進行查找@Autowired(required=false) 表示,如果 spring 上
下文中沒有找到該類型的 bean 時, 纔會使用 new SoftPMServiceImpl();
@Autowired 標註作用於 Map 類型時,如果 Map 的 key 爲 String 類型,則 Spring 會將容器中所有類型符合 Map
的 value 對應的類型的 Bean 增加進來,用 Bean 的 id 或 name 作爲 Map 的 key。
@Autowired 還有一個作用就是,如果將其標註在 BeanFactory 類型、ApplicationContext 類型、ResourceLoader
類型、ApplicationEventPublisher 類型、MessageSource 類型上,那麼 Spring 會自動注入這些實現類的實例,不需要
額外的操作。
@RequestMapping
• 類
@Controller@RequestMapping("/iboy.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)
• 說明
@RequestMapping 可以聲明到類或方法上
• 參數綁定說明
如果我們使用以下的 URL 請求:http://localhost/bbtForum.do?method=listBoardTopic&topicId=1&userId=10&userName=tom
topicId URL 參數將綁定到 topicId 入參上,而 userId 和 userName URL 參數將綁定到 user 對象
的 userId 和 userName 屬性中。和 URL 請求中不允許沒有 topicId 參數不同,雖然 User 的 userId 屬性的類型是基本數
據類型,但如果 URL 中不存在 userId 參數,Spring 也不會報錯,此時 user.userId 值爲 0 。如果 User 對象擁有一
個 dept.deptId 的級聯屬性,那麼它將和 dept.deptId URL 參數綁定。
@RequestParam
參數綁定說明
@RequestParam("id")http://localhost/bbtForum.do?method=listBoardTopic&id=1&userId=10&userName=tom
listBoardTopic(@RequestParam("id")int topicId,User user) 中的 topicId 綁定到 id 這個 URL 參數, 那麼可以通過對入參使用 @RequestParam 註解來達到目的
@RequestParam(required=false):參數不是必須的,默認爲 true
@RequestParam(value="id",required=false)
請求處理方法入參的可選類型
• Java 基本數據類型和 String
默認情況下將按名稱匹配的方式綁定到 URL 參數上,可以通過 @RequestParam 註解改變默認的綁定規則• request/response/session
既可以是 Servlet API 的也可以是 Portlet API 對應的對象,Spring 會將它們綁定到 Servlet 和 Portlet 容器的相應對象上• org.springframework.web.context.request.WebRequest
內部包含了 request 對象• java.util.Locale
綁定到 request 對應的 Locale 對象上• java.io.InputStream/java.io.Reader
可以藉此訪問 request 的內容• java.io.OutputStream / java.io.Writer
可以藉此操作 response 的內容• 任何標註了 @RequestParam 註解的入參
被標註 @RequestParam 註解的入參將綁定到特定的 request 參數上。• java.util.Map / org.springframework.ui.ModelMap
它綁定 Spring MVC 框架中每個請求所創建的潛在的模型對象,它們可以被 Web 視圖對象訪問(如 JSP )• 命令/ 表單對象(注:一般稱綁定使用 HTTP GET 發送的 URL 參數的對象爲命令對象,而稱綁定使用 HTTP POST 發送的 URL 參數的對象爲表單對象)
它們的屬性將以名稱匹配的規則綁定到 URL 參數上,同時完成類型的轉換。而類型轉換的規則可以通過 @InitBinder 註解或通過 HandlerAdapter 的配置進行調整• org.springframework.validation.Errors / org.springframework.validation.BindingResult
• org.springframework.web.bind.support.SessionStatus
可以通過該類型 status 對象顯式結束表單的處理,這相當於觸發 session 清除其中的通過@SessionAttributes 定義的屬性請求處理方法返回值的可選類型• void
此時邏輯視圖名由請求處理方法對應的 URL 確定,如以下的方法:@RequestMapping("/welcome.do")
public void welcomeHandler() {}
對應的邏輯視圖名爲 “ welcome ”
• String
此時邏輯視圖名爲返回的字符,如以下的方法:@RequestMapping(method = RequestMethod.GET)
public String setupForm(@RequestParam("ownerId") int ownerId, ModelMap model) {
Owner owner = this.clinic.loadOwner(ownerId);
model.addAttribute(owner);
return "ownerForm";
}
對應的邏輯視圖名爲 “ ownerForm ”
• org.springframework.ui.ModelMap
和返回類型爲 void 一樣,邏輯視圖名取決於對應請求的 URL ,如下面的例子:@RequestMapping("/vets.do")
public ModelMap vetsHandler() {
return new ModelMap(this.clinic.getVets());
}
對應的邏輯視圖名爲 “ vets ” ,返回的 ModelMap 將被作爲請求對應的模型對象,可以在 JSP 視圖頁面中訪問到。
• ModelAndView
當然還可以是傳統的 ModelAndView 。
@ModelAttribute
• 作用域:request
• 例如
@RequestMapping("/base/userManageCooper/init.do")public String handleInit(@ModelAttribute("queryBean") ManagedUser sUser,Model model,){
• 或者
@ModelAttribute("coopMap")// 將 coopMap 返回到頁面public Map<Long,CooperatorInfo> coopMapItems(){}
• 說明
@ModelAttribute 聲明在屬性上,表示該屬性的 value 來源於 model 裏"queryBean" ,並被保存到 model 裏@ModelAttribute 聲明在方法上,表示該方法的返回值被保存到 model 裏
@Cacheable 和@CacheFlush
• @Cacheable :聲明一個方法的返回值應該被緩存。 例如:@Cacheable(modelId = "testCaching")
• @CacheFlush :聲明一個方法是清空緩存的觸發器。例如:@CacheFlush(modelId = "testCaching")
• 說明
要配合緩存處理器使用。spring3.0 沒有對緩存提供支持,不過 3.1 之後就有了,可以參考:Spring3.1 Cache 註解
@Resource
• 例如
@Resourceprivate DataSource dataSource; // inject the bean named 'dataSource'
• 或者
@Resource(name="dataSource")@Resource(type=DataSource.class)
• 說明
@Resource 默認按 bean 的 name 進行查找,如果沒有找到會按 type 進行查找,此時與@Autowired 類 似
在沒有爲 @Resource 註解顯式指定 name 屬性的前提下,如果將其標註在 BeanFactory 類型、
ApplicationContext 類型、ResourceLoader 類型、 ApplicationEventPublisher 類型、MessageSource 類型上,
那麼 Spring 會自動注入這些實現類的實例,不需要額外的操作。此時 name 屬性不需要指定 ( 或者指定爲""),否則注入
失敗;
@PostConstruct
在方法上加上註解@PostConstruct ,這個方法就會在 Bean 初始化之後被 Spring 容器執 行(注:Bean 初始化包括,實例化 Bean ,並裝配 Bean 的屬性(依賴注入))。
@PreDestroy
在方法上加上註解@PreDestroy ,這個方法就會在 Bean 被銷燬前被 Spring 容器執行。@Repository
• 與@Controller 、@Service 類似,都是向 spring 上下文中註冊 bean ,不在贅述。@Component (不推薦使用)
@Component 是所有受 Spring 管理組件的通用形式,Spring 還提供了更加細化的註解形式: @Repository 、@Service、
@Controller ,它們分別對應存儲層 Bean ,業務層 Bean ,和展示層 Bean 。
目前版本(2.5 )中,這些註解與@Component 的語義是一樣的,完全通用, 在 Spring 以後的版本中可能會給它們追加
更多的語義。 所以,我們推薦使用@Repository 、@Service 、@Controller 來替代@Component 。
@Scope
• 例如
@Scope("session")@Repository()
public class UserSessionBean implementsSerializable {}
• 說明
在使用 XML 定義 Bean 時,可以通過 bean 的 scope 屬性來定義一個 Bean 的作用範圍,同樣可以通過@Scope 註解來完成
@Scope 中可以指定如下值:
singleton:定義 bean 的範圍爲每個 spring 容器一個實例(默認值)
prototype:定義 bean 可以被多次實例化(使用一次就創建一次)
request:定義 bean 的範圍是 http 請求(springMVC 中有效)
session:定義 bean 的範圍是 http 會話(springMVC 中有效)
global-session:定義 bean 的範圍是全局 http 會話(portlet 中有效)
@SessionAttributes
• 說明
Spring 允許我們有選擇地指定 ModelMap 中的哪些屬性需要轉存到 session 中,以便下一個請求屬對應的 ModelMap 的屬性列表中還能訪問到這些屬性。
這一功能是通過類定義處標註 @SessionAttributes 註解來實現的。
@SessionAttributes 只能聲明在類上,而不能聲明在方法上。
• 例如
@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
• 說明
如果希望某個屬性編輯器僅作用於特定的 Controller ,可以在 Controller 中定義一個標註 @InitBinder 註解的方法,
可以在該方法中向 Controller 了註冊若干個屬性編輯器
• 例如
@InitBinderpublic void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
@Required
• 例如
@requiredpublic setName(String name){}
• 說明
@ required 負責檢查一個 bean 在初始化時其聲明的 set 方法是否被執行, 當某個被標註了 @Required 的Setter 方法沒有被調用,則 Spring 在解析的時候會拋出異常,以提醒開發者對相應屬性進行設置。 @Required 註解只
能標註在 Setter 方法之上。因爲依賴注入的本質是檢查 Setter 方法是否被調用了,而不是真的去檢查屬性是否賦值了以
及賦了什麼樣的值。如果將該註解標註在非 setXxxx() 類型的方法則被忽略。
@Qualifier
• 例如
@Autowired@Qualifier("softService")
private ISoftPMService softPMService;
• 說明
使用@Autowired 時,如果找到多個同一類型的 bean,則會拋異常,此時可以使用 @Qualifier("beanName"),明確指定 bean 的名稱進行注入,此時與 @Resource 指定 name 屬性作用相同。