歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Spring常用注解簡述

Spring常用注解簡述

日期:2017/3/1 9:09:26   编辑:Linux編程

使用注解構造IOC、替代傳統的applicationContext.xml配置<bean/>和<property/>

傳統的spring要在applicationContext.xml中配置:①<bean>類 ②<property>屬性 如果有100個類和若干個屬性,那麼我們就要寫成百上千個<bean>、<property>,這種就不利於維護,使用注解就能夠解決這個問題。(項目中的方法也可以使用注解來替代)

在使用類注解前要在applicationContext.xml文件中添加:

<context:component-scan base-package="news"></context:component-scan>

注意:base-package可以指定一個包也可指定多個包,多個包逗號隔開

使用了<context:component-scan/>之後就可以把<context:annotation-config/>移除,因為<context:component-scan/>也能實現掃描包路徑。

1.(類)@Controller

@Controller是對應控制層的<bean>,也就是action類

用法:

1 @Controller
2 @Scope("prototype")
3 public class NewsAction extends ActionSupport{
4 ……
5 }

注意:如果@Controller不指定其value【@Controller】,則默認的bean名字為這個類的類名首字母小寫,如果指定value【@Controller(value="UserAction")】或者【@Controller("UserAction")】,則使用value作為bean的名字。

2、(類)@ Service

@Service對應的是業務層Bean

用法:

1 @Service("NewsService")
2 public class NewsServiceImpl implements NewsService {
3 ………
4 }

3、(類)@ Repository

@Repository對應數據訪問層Bean,部分技術人員也喜歡叫dao類

用法

1 @Repository(value="NewsDao")
2 public class NewsDaoImpl extends NewsDaoImpl {
3 ………
4 }

注意:以上三種(@Controller、@Service、@Repository)是針對不同層的類所使用的注解,下面的是針對屬性所使用的注解:

4.(屬性)@ Autowired (不推薦使用,建議使用@Resource)

@Qualifier("...")

用法(在實現類中封裝一個屬性並私有化,在屬性上面添加@Autowired @Qualifier)

如下:

public class NewsDaoImpl implements NewsDao {
   //這種方式是spring注解
   @Autowired
@Qualifier("mySessionFactory")
private SessionFactory sf;
}

注意:加入@Qualifier是為了讓spring准確地知道要注入的對象,括號裡自定義屬性名字

5.(屬性)@Resource(jdk)

用法:

public class NewsDaoImpl implements NewsDao {
    @Resource(name="mySessionFactory")
    private SessionFactory sf;
}

通過@Resource注解來給屬性sf注入一個名字為mySessionFactory的值

Spring中如何配置Hibernate事務 http://www.linuxidc.com/Linux/2013-12/93681.htm

Struts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htm

基於 Spring 設計並實現 RESTful Web Services http://www.linuxidc.com/Linux/2013-10/91974.htm

Spring-3.2.4 + Quartz-2.2.0集成實例 http://www.linuxidc.com/Linux/2013-10/91524.htm

使用 Spring 進行單元測試 http://www.linuxidc.com/Linux/2013-09/89913.htm

運用Spring注解實現Netty服務器端UDP應用程序 http://www.linuxidc.com/Linux/2013-09/89780.htm

Spring 3.x 企業應用開發實戰 PDF完整高清掃描版+源代碼 http://www.linuxidc.com/Linux/2013-10/91357.htm

Spring 的詳細介紹:請點這裡
Spring 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved