spring和springmvc注解的補充(@Autowired@Resource@Service,@repository,@Component)


注解和注釋以及Spring和SpringMVC常用的注解

SpringMVC 常用注解

springmvc常用注解標簽詳解

 

使用注解都需要在xml配置中增加如下標簽配置:

<!-- 可以掃描controller、service、...
    這里讓掃描controller,指定controller的包
     ps: 該標簽讓指定包下面的類(擁有注解標識的類)注冊到容器-->
    <context:component-scan base-package="cn.itcast.ssm.controller"></context:component-scan>    

 

Spring注解@Resource和@Autowired區別對比

Spring 注解配置(2)——@Autowired

@Resource和@Autowired區別

@Resource 默認按照名稱方式進行bean匹配,
@Autowired默認按照類型方式進行bean匹配
@Resource(import javax.annotation.Resource;)是J2EE的注解,
@Autowired(import org.springframework.beans.factory.annotation.Autowired;)是Spring的注解

共同點

兩者都可以寫在字段和setter方法上。
兩者如果都寫在字段上,那么就不需要再寫setter方法
(ps: 修飾屬性都表示注入該屬性對象)

 

SpringMVC常用注解@Controller,@Service,@repository,@Component一般都標記在類上

@Controller,@Service,@repository,@Component區別

(ps:修飾類都表示該類加入容器)

1、@controller 控制器(注入服務)
2、@service 服務(注入dao)
3、@repository dao(實現dao訪問)
4、@component (把普通pojo實例化到spring容器中,相當於配置文件中的<bean id="" class=""/>)

注意:除了1有特別的意義,234的注解主要mvc分層(1234都具有對象注冊到spring容器的作用)

在Annotaion配置注解中用@Component來表示一個通用注釋用於說明一個類是一個Spring容器管理的類。
即該類已經拉入到Spring的管理中了。
而@Controller, @Service, @Repository是@Component的細化,這三個注解比@Component帶有更多的語義,
它們分別對應了控制層、服務層、持久層的類。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM