spring MVC——標籤及注入

Spring2.5爲我們引入了組件自動掃描機制,他可以在類路徑底下尋找標註了@Component,@Service,@Controller,@Repository註解的類,並把這些類納入進spring容器中管理。它的作用和在xml文件中使用bean節點配置組件時一樣的。當然你要使用annotation就需要使用java5以上版本。

@Component是一個通用註解,用於說明一個類是一個spring容器管理的類。
除此之外,還有@Controller@Service@Repository是@Component的細化,這三個註解比@Component帶有更多的語義,它們分別對應了表現層、服務層、持久層的類。
如果你只是用它們定義bean,你可以僅使用@Component,但是既然spring提供這些細化的註解,那肯定有使用它們的好處,不過在以下的例子中體現不出。

model層——mobile.java

DAO層——mobileDao.java(接口)、mobileDaoHibernate.java(實現前面接口)——@Repository

想要掃描Repository使之起作用要在applicationContext-dao.xml中配置如下

<!-- Activates scanning of @Repository -->
    <context:component-scan base-package="com.xx.dao"/>

@Repository("mobileDao")
public class MobileDaoHibernate extends GenericDaoHibernate<Mobile, Long> implements MobileDao {
	public MobileDaoHibernate() {
        super(Mobile.class);
    }
}
service層——mobileManage.java(接口)mobileManageImpl.java——@Service

首先在appplicationContext-service.xml中

<!-- Activates scanning of @Service -->
    <context:component-scan base-package="com.xx.service"/>
@WebService //java
public interface MobileManager extends GenericManager<Mobile, Long> {   }


@Service("mobileManager")	//spring
@WebService(serviceName = "MobileService", endpointInterface = "com.xx.service.MobileManager")//java
public class MobileManagerImpl extends GenericManagerImpl<Mobile, Long> implements MobileManager {
    MobileDao mobileDao;

    @Autowired
    public MobileManagerImpl(MobileDao mobileDao) {
        super(mobileDao);
        this.mobileDao = mobileDao;
    }}

@Autowired 與@Resource的區別:

 

1、 @Autowired與@Resource都可以用來裝配bean. 都可以寫在字段上,或寫在setter方法上。

2、 @Autowired默認按類型裝配(這個註解是屬業spring的),默認情況下必須要求依賴對象必須存在,如果要允許null值,可以設置它的required屬性爲false,如:@Autowired(required=false) ,如果我們想使用名稱裝配可以結合@Qualifier註解進行使用,如下











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