注解的力量 -----Spring 2.5 JPA hibernate 使用方法的點滴整理(五):使用@Component 來簡化bean的配置...

雖然我們可以通過 @Autowired 在 Bean 類中使用自動注入功能,但是 Bean 還是在 applicatonContext.xml 文件中通過 <bean> 進行定義 —— 在前面的例子中,我們還是在配置文件中定義 Bean,通過 @Autowired為 Bean 的成員變量、方法形參或構造函數形參提供自動注入的功能。

那么能不是也可以通過注解定義 Bean,從 XML 配置文件中完全移除 Bean 定義的配置呢?
答案是肯定的,我們通過 Spring 2.5 提供的 @Component 注釋就可以達到這個目標了。
修改Bean的java類的代碼如下,在類名前面加上 @Component注解
  1. package?com.firemax.test.service;
  2. import?java.util.ArrayList;
  3. import?java.util.Iterator;
  4. import?java.util.List;
  5. import?org.apache.commons.logging.Log;
  6. import?org.apache.commons.logging.LogFactory;
  7. import?org.dom4j.Document;
  8. import?org.dom4j.DocumentHelper;
  9. import?org.dom4j.Element;
  10. import?org.springframework.beans.factory.annotation.Autowired;
  11. import?org.springframework.stereotype.Component;
  12. import?com.firemax.test.hibernate.AlcorTCitys;
  13. import?com.firemax.test.hibernate.AlcorTCitysDAO;
  14. import?com.firemax.test.hibernate.AlcorTCountries;
  15. import?com.firemax.test.hibernate.AlcorTCountriesDAO;
  16. import?com.firemax.test.hibernate.AlcorTProvinces;
  17. import?com.firemax.test.hibernate.AlcorTProvincesDAO;
  18. import?com.firemax.test.hibernate.AlcotTDistrict;
  19. import?com.firemax.test.hibernate.AlcotTDistrictDAO;
  20. @Component
  21. public?class?CountryService?{
  22. ????private?static?Log?logger?=?LogFactory.getLog(CountryService.class);
  23. ????@Autowired
  24. ????private?AlcorTCountriesDAO??alcorTCountriesDAO;
  25. ????@Autowired
  26. ????private?AlcorTProvincesDAO??alcorTProvincesDAO;
  27. ????@Autowired
  28. ????private?AlcorTCitysDAO??????????alcorTCitysDAO;
  29. ????@Autowired
  30. ????private?AlcotTDistrictDAO???????alcotTDistrictDAO;
  31. ????
  32. ????public?CountryService(){
  33. ????????
  34. ????}
  35. ?????//這里是業務邏輯的方法
  36. ?????。。。。。
  37. }
然后,我們修改配置文件applicatonContext.xml中,啟用自動注入的功能,而放棄原來的<bean>方式的配置
  1. <?xml?version="1.0"?encoding="UTF-8"?>
  2. <beans?xmlns="http://www.springframework.org/schema/beans"
  3. ????xmlns:context="http://www.springframework.org/schema/context"
  4. ????xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. ????xmlns:tx="http://www.springframework.org/schema/tx"
  6. ????xsi:schemaLocation="http://www.springframework.org/schema/beans???http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  7. ????????????????????????????????????????????http://www.springframework.org/schema/context??http://www.springframework.org/schema/context/spring-context-2.5.xsd
  8. ????????????????????????????????????????????http://www.springframework.org/schema/tx??http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
  9. ????default-autowire="autodetect">
  10. ????<bean?id="entityManagerFactory"
  11. ????????class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
  12. ????????<property?name="persistenceUnitName"?value="testerPU"?/>
  13. ????</bean>
  14. ????<bean?id="transactionManager"?class="org.springframework.orm.jpa.JpaTransactionManager">
  15. ????????<property?name="entityManagerFactory"?ref="entityManagerFactory"?/>
  16. ????</bean>
  17. ????<tx:annotation-driven?transaction-manager="transactionManager"?/>
  18. ????<bean?id="transactionInterceptor"
  19. ????????class="org.springframework.transaction.interceptor.TransactionInterceptor">
  20. ????????<!--?事務攔截器bean需要依賴注入一個事務管理器?-->
  21. ????????<property?name="transactionManager">
  22. ????????????<ref?local="transactionManager"?/>
  23. ????????</property>
  24. ????????<property?name="transactionAttributes">
  25. ????????????<!--?下面定義事務(指service里面的方法)傳播屬性?-->
  26. ????????????<props>
  27. ????????????????<prop?key="insert*">PROPAGATION_REQUIRED</prop>
  28. ????????????????<prop?key="update*">PROPAGATION_REQUIRED</prop>
  29. ????????????????<prop?key="save*">PROPAGATION_REQUIRED</prop>
  30. ????????????????<prop?key="add*">PROPAGATION_REQUIRED</prop>
  31. ????????????????<prop?key="update*">PROPAGATION_REQUIRED</prop>
  32. ????????????????<prop?key="remove*">PROPAGATION_REQUIRED</prop>
  33. ????????????????<prop?key="delete*">PROPAGATION_REQUIRED</prop>
  34. ????????????????<prop?key="get*">PROPAGATION_REQUIRED,readOnly
  35. ????????????????</prop>
  36. ????????????????<prop?key="find*">PROPAGATION_REQUIRED,readOnly
  37. ????????????????</prop>
  38. ????????????????<prop?key="load*">PROPAGATION_REQUIRED,readOnly
  39. ????????????????</prop>
  40. ????????????????<prop?key="change*">PROPAGATION_REQUIRED</prop>
  41. ????????????????<prop?key="count*">PROPAGATION_REQUIRED</prop>
  42. ????????????????<prop?key="*">PROPAGATION_REQUIRED</prop>
  43. ????????????</props>
  44. ????????</property>
  45. ????</bean>
  46. ????
  47. ????<!--?該?BeanPostProcessor?將自動對標注?@Autowired?的?Bean?進行注入?-->
  48. ????<!--??這個Processor?已經被?<context:annotation-config/>?所簡化???
  49. ????<bean?class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
  50. ????-->
  51. ?????<!--?<context:component-scan/>?配置項不但啟用了對類包進行掃描以實施注釋驅動?Bean?定義的功能,同時還啟用了注釋驅動自動注入的功能(即還隱式地在內部注冊了?AutowiredAnnotationBeanPostProcessor?和?CommonAnnotationBeanPostProcessor),因此當使用?<context:component-scan/>?后,就可以將?<context:annotation-config/>?移除了。?-->
  52. ????<context:component-scan?base-package?="com.firemax"/>??
  53. ????
  54. ????
  55. ????<!--?定義自動代理BeanNameAutoProxyCreator?-->
  56. ????<bean?id="beanNameAutoProxyCreator"
  57. ????????class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
  58. ????????<!--?指定對滿足哪些bean?name的bean自動生成業務代理?-->
  59. ????????<property?name="beanNames">
  60. ????????????<list>
  61. ????????????????<value>*Service</value>
  62. ????????????</list>
  63. ????????</property>
  64. ????????<!--?下面定義BeanNameAutoProxyCreator所需的事務攔截器??-->
  65. ????????<property?name="interceptorNames">
  66. ????????????<list>
  67. ????????????????<!--?此處可增加其他新的Interceptor?-->
  68. ????????????????<value>transactionInterceptor</value>
  69. ????????????</list>
  70. ????????</property>
  71. ????</bean>
  72. ????<!--?
  73. ????<bean?id="AlcorTCountriesDAO"?class="com.firemax.test.hibernate.AlcorTCountriesDAO">
  74. ????????<property?name="entityManagerFactory"?ref="entityManagerFactory"?/>
  75. ????</bean>
  76. ????<bean?id="AlcorTProvincesDAO"?class="com.firemax.test.hibernate.AlcorTProvincesDAO">
  77. ????????<property?name="entityManagerFactory"?ref="entityManagerFactory"?/>
  78. ????</bean>
  79. ????<bean?id="AlcotTDistrictDAO"?class="com.firemax.test.hibernate.AlcotTDistrictDAO">
  80. ????????<property?name="entityManagerFactory"?ref="entityManagerFactory"?/>
  81. ????</bean>
  82. ????<bean?id="AlcorTCitysDAO"?class="com.firemax.test.hibernate.AlcorTCitysDAO">
  83. ????????<property?name="entityManagerFactory"?ref="entityManagerFactory"?/>
  84. ????</bean>
  85. ????
  86. ?????<bean?id="CountryService"?class="com.firemax.test.service.CountryService"/>
  87. ????-->
  88. </beans>
新的applicaitonContext.xml 配置文件中藍色的部分就是原來的<bean>的注入方式,現在已經給屏蔽了。不需要再寫。而紅色部分就是使用了<context:component-scan?base-package?="com.firemax"/> ,讓spirng自動搜索,然后注入。
注意:
  • 這里注入的bean 的名稱是按照類的名稱,把第一個字母改成小寫來命名的。比如例子中的CountryService的bean的名稱就是countryService.
  • 我們也可以通過@Component("countryService") 這種方式來顯示的定義一個bean的注入名稱。但是在大多數情況下沒有必要。

<context:component-scan/> 的 base-package 屬性指定了需要掃描的類包,類包及其遞歸子包中所有的類都會被處理。

<context:component-scan/> 還允許定義過濾器將基包下的某些類納入或排除。Spring 支持以下 4 種類型的過濾方式,通過下表說明:


?掃描過濾方式
過濾器類型說明
注釋假如 com.firemax.test.SomeAnnotation 是一個注釋類,我們可以將使用該注釋的類過濾出來。
類名指定通過全限定類名進行過濾,如您可以指定將?com.firemax.test.IncludeService納入掃描,而將 com.firemax.test.NotIncludeService 排除在外。
正則表達式通過正則表達式定義過濾的類,如下所示: com/.firemax/.test/.Default.*
AspectJ 表達式通過 AspectJ 表達式定義過濾的類,如下所示: com. firemax.test..*Service+

下面是一個簡單的例子:

  1. <context:component-scan?base-package="com.firemax">
  2. ????<context:include-filter?type="regex"?
  3. ????????expression="com/.firemax/.test/.service/..*"/>
  4. ????<context:exclude-filter?type="aspectj"?
  5. ????????expression="com.firemax.test.util..*"/>
  6. </context:component-scan>

默認情況下通過?@Component?定義的 Bean 都是 singleton 的,如果需要使用其它作用范圍的 Bean,可以通過?@Scope?注釋來達到目標,如以下代碼所示:


?通過 @Scope 指定 Bean 的作用范圍
  1. ????????????????
  2. package?com.firemax.tester.service;
  3. import?org.springframework.context.annotation.Scope;
  4. @Scope("prototype")
  5. @Component("countryService")
  6. public?class?CountryService{
  7. ????…
  8. }

這樣,當從 Spring 容器中獲取?boss?Bean 時,每次返回的都是新的實例了。

?

在Spring2.5中引入了更多的典型化注解,@Repository ,@Service,@Controler是@Component的細化。分別表示持久層,服務層,控制層。建議使用這個注解來取代@Component

?

附上一個java Applicaiton的簡單測試程序

?

  1. /*
  2. ?*?Created?on?2008-9-28
  3. ?*
  4. ?*?徐澤宇?roamer
  5. ?*/
  6. package?com.firemax.test.tester;
  7. import?java.util.Iterator;
  8. import?org.springframework.context.ApplicationContext;
  9. import?org.springframework.context.support.FileSystemXmlApplicationContext;
  10. import?com.firemax.test.hibernate.AlcorTCitys;
  11. import?com.firemax.test.hibernate.AlcorTCitysDAO;
  12. import?com.firemax.test.hibernate.AlcorTCountries;
  13. import?com.firemax.test.hibernate.AlcorTProvinces;
  14. import?com.firemax.test.hibernate.AlcotTDistrict;
  15. import?com.firemax.test.hibernate.AlcotTDistrictDAO;
  16. import?com.firemax.test.service.CountryService;
  17. public?class?Tester?{
  18. ????/**
  19. ?????*?@param?args
  20. ?????*/
  21. ????public?static?void?main(String[]?args)?throws?Exception{
  22. ????????//?TODO?Auto-generated?method?stub
  23. ????????ApplicationContext?ctx?=?????new?FileSystemXmlApplicationContext("/WebContent/WEB-INF/classes/applicationContext*.xml");
  24. ????????String[]?beans?=?ctx.getBeanDefinitionNames();
  25. ????????for?(int?i?=?0?;?i?<?beans.length;i++)
  26. ????????{
  27. ????????????System.out.println(beans[i]);
  28. ????????}
  29. ????????CountryService?countryService=?(CountryService)ctx.getBean("countryService");
  30. ??????
  31. ????????AlcorTCountries??alcorTCountries=?countryService.getCountriesInfo("CN");
  32. ????????System.out.println(alcorTCountries.getCountry());
  33. ????????System.out.println("開始調用子類");
  34. ????????System.out.println(alcorTCountries.getAlcorTProvinceses().size());
  35. ????????Iterator<AlcorTProvinces>?it?=?alcorTCountries.getAlcorTProvinceses().iterator();
  36. ????????while?(it.hasNext()){
  37. ????????????AlcorTProvinces??alcorTProvinces=?(AlcorTProvinces)it.next();
  38. ????????????System.out.println(alcorTProvinces.getProvinceName());
  39. ????????}
  40. ????????AlcotTDistrict?alcotTDistrict=?new?AlcotTDistrict();
  41. ????????alcotTDistrict.setDistrictCode("22");
  42. ????????alcotTDistrict.setDistrictName("浦東");
  43. ????????AlcorTCitys?alcorTCitys?=countryService.getCityInfo("021");
  44. ????????alcotTDistrict.setAlcorTCitys(alcorTCitys);
  45. ????????countryService.saveProvinces(alcotTDistrict);
  46. ????????
  47. ????}
  48. }
在所有的JPOPO中,我們可以使用@Entity 這個注解來注入 JOPO。這樣我們在 Persistent.xml中就不需要在 定義哪些POJO的類了。

?

感謝 JPA 感謝Spring ,終于不要頻繁的去定義和修改這些Bean了

?

?

?

原文網址:http://blog.csdn.net/remote_roamer/article/details/3008016

轉載于:https://www.cnblogs.com/winkey4986/archive/2012/02/16/2355023.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/377741.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/377741.shtml
英文地址,請注明出處:http://en.pswp.cn/news/377741.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

c語言條件語句示例_PHP中的條件語句和示例

c語言條件語句示例PHP條件語句 (PHP Conditional Statements) While coding, you may get to a point where your results can only be gotten when a condition is valid. We make use of conditional statements. Conditional statements are statements that can only be ex…

十四、聚類實戰——圖片壓縮

對同一像素點值的像素點歸為一類&#xff0c;通過平均值進行取代&#xff0c;從而將圖像進行壓縮并且保證圖像盡可能不失真&#xff0c;關鍵信息仍保留。 from PIL import Image import numpy as np from sklearn.cluster import KMeans import matplotlib import matplotlib.…

步驟菜單使用css3實現

代碼庫&#xff1a;http://thecodeplayer.com/walkthrough/css3-breadcrumb-navigation 有興趣的可以看一下&#xff0c;看完絕對讓你大飽眼福。首先截圖&#xff0c;看效果看著很酷吧&#xff0c;其實實現起來也不是很難&#xff0c;里邊需要用的技術有:box-shadow,計數器&…

【嵌入式系統】STM32串口通信的四種方法(基于RTOS)

目錄1、串行通信的基本參數2、輪詢方式代碼效果3、中斷方式代碼效果4、中斷加上時間戳方式代碼及效果5、DMA空閑中斷方式接收數據1、串行通信的基本參數 串行端口的通信方式是將字節拆分成一個接一個的位再傳輸出去&#xff0c;接收方再將此一個一個的位組合成原來的字符&…

大數據 java 代碼示例_Java變量類型與示例

大數據 java 代碼示例Java變量 (Java variables) Variables are the user-defined names of the memory blocks, and their values can be changed at any time during program execution. They play an important role in a class/program as they help in to store, retrieve…

畢業設計

位置跟蹤系統工作原理&#xff08;博聞網&#xff09; http://science.bowenwang.com.cn/location-tracking.htm Azuma是這樣定義增強現實的 :虛實結合 ,實時交互 ,三維注冊 環境搭建&#xff1a; http://cvchina.net/thread-173-1-1.html http://blog.csdn.net/jdh99/article/…

十五、聚類的評估

一、Given Label 均一性homogeneity&#xff1a;一個簇中只包含一個類別樣本&#xff0c;Precision 完整性completeness&#xff1a;同類別樣本被歸到同一個簇中&#xff0c;Recall 將均一性h和完整性c進行結合(二者加權平均)得到V-Measure&#xff0c;&#xff0c;β為權重 …

SQL SERVER作業的Schedules淺析

SQL SERVER作業的計劃&#xff08;Schedules&#xff09;&#xff0c;如果你沒仔細研究過或沒有應用一些復雜的計劃&#xff08;Schedules&#xff09;&#xff0c;那么你覺得SQL SERVER作業的計劃(Schedules)非常好用&#xff0c;也沒啥問題&#xff0c;但是我要告訴你一個“殘…

leetcode 51. N 皇后 思考分析

目錄題目思考AC代碼題目 n 皇后問題研究的是如何將 n 個皇后放置在 nn 的棋盤上&#xff0c;并且使皇后彼此之間不能相互攻擊。 思考 首先以N4為例&#xff0c;畫出解空間樹的一部分&#xff1a; 根據模板&#xff1a; void backtracking(參數) {if(終止條件){存放結果…

Django實戰(18):提交訂單

前面的內容已經基本上涵蓋了Django開發的主要方面&#xff0c;我們從需求和界面設計出發&#xff0c;創建模型和修改模型&#xff0c;并通過scaffold作為開發的起點&#xff1b;在scaffold的基礎上重新定制模板&#xff0c;并且通過Model類和Form類對用戶輸入的數據進行校驗。我…

No module named ‘tensorflow.examples‘解決方案

想從tensorflow中導入mnist手寫數字數據集&#xff0c;結果報錯 from tensorflow.examples.tutorials.mnist import input_data import tensorflow.compat.v1 as tf tf.disable_v2_behavior()my_mnist input_data.read_data_sets("MNIST_data_bak/", one_hotTrue)&…

julia example_使用Julia中的Example的sign()函數

julia exampleJulia| sign()函數 (Julia | sign() function) sign() function is a library function in Julia programming language, it returns the sign of the given value in the form of -1/1. sign()函數是Julia編程語言中的庫函數&#xff0c;它以-1 / 1的形式返回給…

.NET通用基本權限系統

DEMO下載地址&#xff1a; http://download.csdn.net/detail/shecixiong/5372895 一、開發技術&#xff1a;B/S(.NET C# ) 1、Windows XP以上 (支援最新Win 8) 2、Microsoft Visual Studio 2010/2012 C#.NET 3、.NET Framework 4.0以上 (支援最新4.5版本) 4、SQL Server 2005以…

leetcode 37. 解數獨 思考分析

目錄題目核心思路的不斷細化1、核心框架2、考慮到每個位置的工作3、考慮到到達最后一列、該位置的數已經預置的情況4、判斷是否符合規則的函數5、確定遞歸終止條件確定函數返回值AC代碼題目 編寫一個程序&#xff0c;通過填充空格來解決數獨問題。 一個數獨的解法需遵循如下規…

快速完成兼職外包開發任務

做了很多年的開發相關的工作&#xff0c;做過兼職開發&#xff0c;也做過外包一些開發項目。 兼職人員角色時 正是經歷這些事情時&#xff0c;每次就要提前很費經的跟公司溝通&#xff0c;讓他們把公司內部的svn開發出去&#xff0c;但是就是很難&#xff0c;會涉及到安全各方的…

使用YOLOv5訓練NEU-DET數據集

一、下載YOLOv5源碼和NEU-DET(鋼材表面缺陷)數據集 YOLOv5源碼 NEU-DET(鋼材表面缺陷)數據集 這里的數據集已經經過處理了&#xff0c;下載即可 若通過其他途徑下載的原始數據集標簽為xml格式&#xff0c;需要轉化為txt格式XML轉txt格式腳本 二、數據集準備 NEU-DET(鋼材表…

kotlin獲取屬性_Kotlin程序獲取系統MAC地址

kotlin獲取屬性The task is to get system MAC address. 任務是獲取系統MAC地址。 package com.includehelpimport java.net.InetAddressimport java.net.NetworkInterface//Function to get System MACfun getSystemMac(): String? {return try {val OSName System.getProp…

帶分頁功能的SSH整合,DAO層經典封裝

任何一個封裝講究的是&#xff0c;使用&#xff0c;多狀態。Action&#xff1a;任何一個Action繼承分頁有關參數類PageManage&#xff0c;自然考慮的到分頁效果&#xff0c;我們必須定義下幾個分頁的參數。并根據這個參數進行查值。然后在繼承ServiceManage&#xff0c;Service…

在windows phone Mango中使用原生代碼開發程序

本文不討論創建可執行的exe程序,主要想說明怎么在silverlight程序里面調用由原生代碼所編寫的DLL(C / ARM). 原生代碼可以調用更多的API,但是這并不是說你就能隨意獲得那些你沒有權限的資源,比如,你可以使用CopyFile這個API,但是如果你試圖把文件Copy到\Windows文件夾,就會得到…

leetcode 198. 打家劫舍 思考分析

目錄1、題目2、求解思路3、代碼1、題目 你是一個專業的小偷&#xff0c;計劃偷竊沿街的房屋。每間房內都藏有一定的現金&#xff0c;影響你偷竊的唯一制約因素就是相鄰的房屋裝有相互連通的防盜系統&#xff0c;如果兩間相鄰的房屋在同一晚上被小偷闖入&#xff0c;系統會自動…