Spring註解解釋

Spring註解可以實現快速實例注入,而無需進行繁雜的xml配置。
原文地址:http://bbs.51cto.com/thread-1136892-1.html

  • @Controller
  • @Service
  • @Autowired
  • @RequestMapping
  • @RequestParam
  • @ModelAttribute
  • @Cacheable
  • @CacheFlush
  • @Resource
  • @PostConstruct
  • @PreDestroy
  • @Repository
  • @Component (不推薦使用)
  • @Scope
  • @SessionAttributes
  • @InitBinder
  • @Required
  • @Qualifier

@Controller

@Controller
public class SoftCreateController extends SimpleBaseController {}

@Controller("softCreateController")

@Controller負責註冊一個bean到Spring上下文中,bean的ID默認爲類名稱開頭字母小寫

@Service

@Service
public class SoftCreateServiceImpl implements ISoftCreateService {}

@Service("softCreateServiceImpl")

@Service負責註冊一個bean到Spring上下文中,bean的ID默認爲類名稱開頭字母小寫

@Autowired

@Autowired
private ISoftPMService softPMService;

@Autowired(required=false)
private ISoftPMService softPMService = new SoftPMServiceImpl();

@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("/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)

@RequestMapping可以聲明到類或方法上

@RequestParam

如果我們使用以下的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(required=false):參數不是必須的,默認爲true
@RequestParam(value=”id”,required=false)

@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")

說明:要配合緩存處理器使用,
參考: http://hanqunfeng.iteye.com/blog/603719

@Resource

@Resource
private 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 和@PreDestroy

@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。
Spring2.5版本中,這些註解與@component的語義是一樣的,完全通用,在Spring 以後的版本中可能會給它們追加更多的語義。所以,我們推薦使用@repository 、@Service 、@Controller來替代@component。

@scope

@Scope("session")
@Repository()
public class UserSessionBean implements Serializable {}

在使用XML定義Bean時,可以通過bean的scope屬性來定義一個Bea 的作用範圍,同樣可以通過@scope註解來完成。

@Scope中可以指定如下值:
1. singleton:定義bean的範圍爲每個Spring容器一個實例(默認值)
2. prototype:定義bean可以被多次實例化(使用一次就創建一次)
3. request:定義bean的範圍是http請求(SpringMVC中有效)
4. session:定義bean的範圍是http會話(SpringMVC中有效)
5. 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了註冊若干個屬性編輯器

@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){} 

@Required負責檢查一個bean在初始化時其聲明的set方法是否被執行,當某個被標註了@Required的Setter方法沒有被調用,則Spring在解析的時候會拋出異常,以提醒開發者對相應屬性進行設置。 @Required註解只能標註在 Setter方法之上。因爲依賴注入的本質是檢查Setter方法是否被調用了,而不是真的去檢查屬性是否賦值了以及賦了什麼樣的值。如果將該註解標註在非setXxxx()類型的方法則被忽略。

@Qualifier

@Autowired
@Qualifier("softService")
private ISoftPMService softPMService; 

使用@Autowired時,如果找到多個同一類型的bean,則會拋異常,此時可以使用@Qualifier(“beanName”),明確指定bean的名稱進行注入,此時與@Resource指定name屬性作用相同。

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