Spring(四)使用注解注入Bean


注解簡單介紹

  1. 是代碼里面的特殊標記,使用注解完成功能。
  2. 注解寫法@ 注解名稱(屬性名=屬性值)。
  3. 注解可以作用在類、方法、屬性上面。

使用流程:

  • 在ApplicationContext.xml中開啟注解掃描:

      <!-- 使用Annotation自動注冊Bean,解決事物失效問題:在主容器中不掃描@Controller注解,在SpringMvc中只掃描@Controller注解。  -->
      <!-- 他會默認掃描com.zhiyou100.crm包下及其子包的所有 有@Controller @Service @Repository @resourse
      	這些注解的類,會把這些對象實例化之后放入容器中.	 -->
      <context:component-scan base-package="com.zhiyou100.crm"><!-- base-package 如果多個,用“,”分隔 -->
      	<!-- 告訴主容器不要掃描加有@Controller 這些類,這些bean 是由web容器進行管理的  -->
      	<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
      </context:component-scan>
    
  • 在Spring-MVC中開啟注解掃描:

      <!-- 使用Annotation自動注冊Bean,只掃描@Controller 
      use-default-filters="true"
       默認掃描指定包下的全部 @Component(@Controller/@Service/@Repository), exclude-filter 指定的不掃描,include-filter指定的掃描, 
       include-filter和exclude-filter 沒有指定的仍然掃描,假設一個service被掃描兩次,有可能導致事物失效
       use-default-filters="false"
       include-filter指定的掃描 ,其他沒有指定的不掃描
      -->
      <context:component-scan base-package="com.zhiyou100.crm.controller" use-default-filters="false"><!-- base-package 如果多個,用“,”分隔 -->
      	<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
      </context:component-scan>
    
  • 在類、方法、屬性上添加注解即可。

常用注解說明

在類上,寫@scope注解來將類的創建方式修改為單實例或是多實例等

Spring注入屬性:

  1. 自動注入: @Autowired
  2. 手動注入: @Resource(name="name")

在類上的四個注解如@Service中寫value值如@Service(value="userService")的作用是,當不使用自動注入而采用@Resources注入的時候,在@Resource(name="userService"),這樣可以將屬性與某個類精確的結合起來,而不是由pool分配.


免責聲明!

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



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