九九热99久久久国产盗摄,国产一区二区三区免费在线观看,欧美午夜视频http://www.aygfsteel.com/stevenjohn/category/52035.html那些青春的歲月zh-cnMon, 07 Sep 2015 14:47:19 GMTMon, 07 Sep 2015 14:47:19 GMT60Spring什么時候實例化beanhttp://www.aygfsteel.com/stevenjohn/archive/2015/04/20/424549.htmlabinabinMon, 20 Apr 2015 07:01:00 GMThttp://www.aygfsteel.com/stevenjohn/archive/2015/04/20/424549.htmlhttp://www.aygfsteel.com/stevenjohn/comments/424549.htmlhttp://www.aygfsteel.com/stevenjohn/archive/2015/04/20/424549.html#Feedback0http://www.aygfsteel.com/stevenjohn/comments/commentRss/424549.htmlhttp://www.aygfsteel.com/stevenjohn/services/trackbacks/424549.htmlSpring什么時候實例化bean,首先要分2種情況 
  第一:如果你使用BeanFactory作為Spring Bean的工廠類,則所有的bean都是在第一次使用該Bean的時候實例化 
  第二:如果你使用ApplicationContext作為Spring Bean的工廠類,則又分為以下幾種情況: 
       (1):如果bean的scope是singleton的,并且lazy-init為false(默認是false,所以可以不用設置),則ApplicationContext啟動的時候就實例化該Bean,并且將實例化的Bean放在一個map結構的緩存中,下次再使用該Bean的時候,直接從這個緩存中取 
       (2):如果bean的scope是singleton的,并且lazy-init為true,則該Bean的實例化是在第一次使用該Bean的時候進行實例化 
       (3):如果bean的scope是prototype的,則該Bean的實例化是在第一次使用該Bean的時候進行實例化 


1、lazy init 在getBean時實例化 
2、非lazy的單例bean 容器初始化時實例化 
3、prototype等 getBean時實例化




spring三種實例化bean的方式

在spring中有三中實例化bean的方式:

一、使用構造器實例化;

二、使用靜態工廠方法實例化;

三、使用實例化工廠方法實例化。

 

每種實例化所采用的配置是不一樣的:

一、使用構造器實例化;

這種實例化的方式可能在我們平時的開發中用到的是最多的,因為在xml文件中配置簡單并且也不需要額外的工廠類來實現。

<!--applicationContext.xml配置:-->

<bean id="personService" class="cn.mytest.service.impl.PersonServiceBean"></bean>
 id是對象的名稱,class是要實例化的類,然后再通過正常的方式進調用實例化的類即可,比如:
public void instanceSpring(){
                //加載spring配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext(
new String[]{
"/conf/applicationContext.xml"
});
//調用getBean方法取得被實例化的對象。
PersonServiceBean psb = (PersonServiceBean) ac.getBean("personService");
psb.save();
}

采用這種實例化方式要注意的是:要實例化的類中如果有構造器的話,一定要有一個無參的構造器。

 

二、使用靜態工廠方法實例化;

根據這個中實例化方法的名稱就可以知道要想通過這種方式進行實例化就要具備兩個條件:(一)、要有工廠類及其工廠方法;(二)、工廠方法是靜態的。OK,知道這兩點就好辦了,首先創建工程類及其靜態方法:

package cn.mytest.service.impl;
/**
*創建工廠類
*
*/
public class PersonServiceFactory {
    //創建靜態方法
public static PersonServiceBean createPersonServiceBean(){
         //返回實例化的類的對象
return new PersonServiceBean();
}
}
然后再去配置spring配置文件,配置的方法和上面有點不同,這里也是關鍵所在
<!--applicationContext.xml配置:-->
<bean id="personService1" class="cn.mytest.service.impl.PersonServiceFactory" factory-method="createPersonServiceBean"></bean>

 id是實例化的對象的名稱,class是工廠類,也就實現實例化類的靜態方法所屬的類,factory-method是實現實例化類的靜態方法。

然后按照正常的調用方法去調用即可:

public void instanceSpring(){
                //加載spring配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext(
new String[]{
"/conf/applicationContext.xml"
});
//調用getBean方法取得被實例化的對象。
PersonServiceBean psb = (PersonServiceBean) ac.getBean("personService1");
psb.save();
}

三、使用實例化工廠方法實例化。

這個方法和上面的方法不同之處在與使用該實例化方式工廠方法不需要是靜態的,但是在spring的配置文件中需要配置更多的內容,,首先創建工廠類及工廠方法:

package cn.mytest.service.impl;
/**
*創建工廠類
*
*/
public class PersonServiceFactory {
    //創建靜態方法
public PersonServiceBean createPersonServiceBean1(){
         //返回實例化的類的對象
return new PersonServiceBean();
}
}
然后再去配置spring配置文件,配置的方法和上面有點不同,這里也是關鍵所在
<!--applicationContext.xml配置:-->
<bean id="personServiceFactory" class="cn.mytest.service.impl.PersonServiceFactory"></bean>
<bean id="personService2" factory-bean="personServiceFactory" factory-method="createPersonServiceBean1"></bean>

 這里需要配置兩個bean,第一個bean使用的構造器方法實例化工廠類,第二個bean中的id是實例化對象的名稱,factory-bean對應的被實例化的工廠類的對象名稱,也就是第一個bean的id,factory-method是非靜態工廠方法。

 

 

然后按照正常的調用方法去調用即可:

public void instanceSpring(){
                //加載spring配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext(
new String[]{
"/conf/applicationContext.xml"
});
//調用getBean方法取得被實例化的對象。
PersonServiceBean psb = (PersonServiceBean) ac.getBean("personService2");
psb.save();
}


abin 2015-04-20 15:01 發表評論
]]>
Spring AOP AspectJ http://www.aygfsteel.com/stevenjohn/archive/2015/04/20/424535.htmlabinabinSun, 19 Apr 2015 18:07:00 GMThttp://www.aygfsteel.com/stevenjohn/archive/2015/04/20/424535.htmlhttp://www.aygfsteel.com/stevenjohn/comments/424535.htmlhttp://www.aygfsteel.com/stevenjohn/archive/2015/04/20/424535.html#Feedback0http://www.aygfsteel.com/stevenjohn/comments/commentRss/424535.htmlhttp://www.aygfsteel.com/stevenjohn/services/trackbacks/424535.htmlAOP

面向切面編程(AOP)通過提供另外一種思考程序結構的途經來彌補面向對象編程(OOP)的不足。在OOP中模塊化的關鍵單元是類(classes),而在AOP中模塊化的單元則是切面。切面能對關注點進行模塊化,例如橫切多個類型和對象的事務管理。(在AOP術語中通常稱作橫切(crosscutting)關注點。)

AOP框架是Spring的一個重要組成部分。但是Spring IoC容器并不依賴于AOP,這意味著你有權利選擇是否使用AOP,AOP做為Spring IoC容器的一個補充,使它成為一個強大的中間件解決方案。

AOP即Aspect-Oriented Programming的縮寫,中文意思是面向切面(或方面)編程。AOP實際上是一種編程思想,可以通過預編譯方式和運行期動態代理實現在不修改源代碼的情況下給程序動態統一添加功能的一種思想。

AOP在Spring Framework中的作用

  • 提供聲明式企業服務,特別是為了替代EJB聲明式服務。最重要的服務是聲明性事務管理

  • 允許用戶實現自定義切面,用AOP來完善OOP的使用。

目前AOP主要有:Spring AOP ,JBOSS AOP ,AspectJ AOP

AOP與OOP:可以理解為OOP是縱向的采用繼承樹形式的。而AOP是橫向的

Spring AOP:

由于Spring AOP是容易實現的,如果你計劃在Spring Beans之上將橫切關注點模塊化,Spring的這一目標將是要點之一。但同樣的目標也可能成為一個限制,如果你用的是普通的Java對象而不是Spring beans,并基于此將橫切關注點模塊化的話。另一方面,AspectJ可用于基于普通Java對象的模塊化,但在實施之前需要良好的關于這個主題的知識。
 
Spring AOP致力于提供一種能夠與Spring IoC緊密集成的面向方面框架的實現,以便于解決在開發企業級項目時面臨的常見問題。明確你在應用橫切關注點(cross-cutting concern)時(例如事物管理、日志或性能評估),需要處理的是Spring beans還是POJO。如果正在開發新的應用,則選擇Spring AOP就沒有什么阻力。但是如果你正在維護一個現有的應用(該應用并沒有使用Spring框架),AspectJ就將是一個自然的選擇了。為了詳細說明這一點,假如你正在使用Spring AOP,當你想將日志功能作為一個通知(advice)加入到你的應用中,用于追蹤程序流程,那么該通知(Advice)就只能應用在Spring beans的連接點(Joinpoint)之上。
 

AspectJ AOP:

使用“AspectJ”你可以在任何Java對象上應用通知,而不需要在任何文件中創建或配置任何bean。
 

另一個需要考慮的因素是,你是希望在編譯期間進行織入(weaving),還是編譯后(post-compile)或是運行時(run-time)。Spring只支持運行時織入。如果你有多個團隊分別開發多個使用Spring編寫的模塊(導致生成多個jar文件,例如每個模塊一個jar文件),并且其中一個團隊想要在整個項目中的所有Spring bean(例如,包括已經被其他團隊打包了的jar文件)上應用日志通知(在這里日志只是用于加入橫切關注點的舉例),那么通過配置該團隊自己的Spring配置文件就可以輕松做到這一點。之所以可以這樣做,就是因為Spring使用的是運行時織入。

 因為Spring基于代理模式(使用CGLIB),它有一個使用限制,即無法在使用final修飾的bean上應用橫切關注點。因為代理需要對Java類進行繼承,一旦使用了關鍵字final,這將是無法做到的。

在這種情況下,你也許會考慮使用AspectJ,其支持編譯期織入且不需要生成代理。


于此相似,在static和final方法上應用橫切關注點也是無法做到的。因為Spring基于代理模式。如果你在這些方法上配置通知,將導致運行時異常,因為static和final方法是不能被覆蓋的。在這種情況下,你也會考慮使用AspectJ,因為其支持編譯期織入且不需要生成代理。
 
缺點:
使用AspectJ的一個間接局限是,因為AspectJ通知可以應用于POJO之上,它有可能將通知應用于一個已配置的通知之上。對于一個你沒有注意到這方面問題的大范圍應用的通知,這有可能導致一個無限循環。
 

面向切面編程,把散落在程序中的公共部分提取出來,做成切面類,這樣的好處在于,代碼的可重用,一旦涉及到該功能的需求發生變化,只要修改該代碼就行,否則,你要到處修改,如果只要修改1、2處那還可以接受,萬一有1000處呢。 
AOP底層的東西就是JDK動態代理和CGLIB代理,說白了就是增強類的功能。 
最常用的AOP應用在數據庫連接以及事務處理上。

AOP:面向切面編程。(Aspect-Oriented Programming)
AOP可以說是對OOP的補充和完善。OOP引入封裝、繼承和多態性等概念來建立一種對象層次結構,用以模擬公共行為的一個集合。當我們需要為分散的對象引入公共行為的時候,OOP則顯得無能為力。也就是說,OOP允許你定義從上到下的關系,但并不適合定義從左到右的關系。例如日志功能。日志代碼往往水平地散布在所有對象層次中,而與它所散布到的對象的核心功能毫無關系。在OOP設計中,它導致了大量代碼的重復,而不利于各個模塊的重用。
將程序中的交叉業務邏輯(比如安全,日志,事務等),封裝成一個切面,然后注入到目標對象(具體業務邏輯)中去。

實現AOP的技術,主要分為兩大類:一是采用動態代理技術,利用截取消息的方式,對該消息進行裝飾,以取代原有對象行為的執行;二是采用靜態織入的方式,引入特定的語法創建“方面”,從而使得編譯器可以在編譯期間織入有關“方面”的代碼.

 AOP(Aspect Orient Programming),作為面向對象編程的一種補充,廣泛應用于處理一些具有橫切性質的系統級服務,如事務管理、安全檢查、緩存、對象池管理等。 AOP 實現的關鍵就在于 AOP 框架自動創建的 AOP 代理,AOP 代理則可分為靜態代理和動態代理兩大類,其中靜態代理是指使用 AOP 框架提供的命令進行編譯,從而在編譯階段就可生成 AOP 代理類,因此也稱為編譯時增強;而動態代理則在運行時借助于 JDK 動態代理、CGLIB 等在內存中"臨時"生成 AOP 動態代理類,因此也被稱為運行時增強。











abin 2015-04-20 02:07 發表評論
]]>
spring IOC控制反轉http://www.aygfsteel.com/stevenjohn/archive/2015/04/15/424435.htmlabinabinWed, 15 Apr 2015 05:36:00 GMThttp://www.aygfsteel.com/stevenjohn/archive/2015/04/15/424435.htmlhttp://www.aygfsteel.com/stevenjohn/comments/424435.htmlhttp://www.aygfsteel.com/stevenjohn/archive/2015/04/15/424435.html#Feedback0http://www.aygfsteel.com/stevenjohn/comments/commentRss/424435.htmlhttp://www.aygfsteel.com/stevenjohn/services/trackbacks/424435.htmlSpring框架的核心就是控制反轉(Inversion of Control)和依賴注入(Dependency Injection),通過這兩方面來實現松耦合。

使用IoC,對象是被動的接受依賴類,而不是自己主動的去找。容器在實例化的時候主動將它的依賴類注入給它。可以這樣理解:控制反轉將類的主動權轉移到接口上,依賴注入通過xml配置文件在類實例化時將其依賴類注入。

    依賴類(Dependency)是通過外部(xml)來注入的,而不是由使用它的類(Business)來自己制造,這就是依賴的注入。另一方面,Business對類Dependency的依賴轉移到對接口IDependency的依賴,控制權由類轉移到了接口,即由"實現"轉移到"抽象"中。這就是控制反轉。
 
使用IoC,對象是被動的接受依賴類,而不是自己主動的去找。容器在實例化的時候主動將它的依賴類注入給它。可以這樣理解:控制反轉將類的主動權轉移到接口上,依賴注入通過xml配置文件在類實例化時將其依賴類注入。

控制反轉即IoC (Inversion of Control),它把傳統上由程序代碼直接操控的對象的調用權交給容器,通過容器來實現對象組件的裝配和管理。所謂的“控制反轉”概念就是對組件對象控制權的轉移,從程序代碼本身轉移到了外部容器。

依賴注入(Dependency Injection)和控制反轉(Inversion of Control)是同一個概念。具體含義是:當某個角色(可能是一個Java實例,調用者)需要另一個角色(另一個Java實例,被調用者)的協助時,在傳統的程序設計過程中,通常由調用者來創建被調用者的實例。但在Spring里,創建被調用者的工作不再由調用者來完成,因此稱為控制反轉;創建被調用者實例的工作通常由Spring容器來完成,然后注入調用者,因此也稱為依賴注入。
  簡而言之:所謂控制反轉就是應用本身不負責依賴對象的創建及維護,依賴對象的創建及維護是由外部容器負責的。這樣控制權就由應用轉移到了外部容器,控制權的轉移就是所謂反轉;所謂依賴注入就是指:在運行期,由外部容器動態地將依賴對象注入到組件中。


傳統編程和IoC的對比
傳統編程:決定使用哪個具體的實現類的控制權在調用類本身,在編譯階段就確定了。
IoC模式:調用類只依賴接口,而不依賴具體的實現類,減少了耦合。控制權交給了容器,在運行的時候才由容器決定將具體的實現動態的“注入”到調用類的對象中。


應用控制反轉,對象在被創建的時候,由一個調控系統內所有對象的外界實體將其所依賴的對象的引用傳遞給它。也可以說,依賴被注入到對象中。所以,控制反轉是,關于一個對象如何獲取他所依賴的對象的引用,這個責任的反轉。


IoC核心理念:

1.在類當中不創建對象,在代碼中不直接與對象和服務連接

2.在配置文件中描述創建對象的方式,以及各個組件之間的聯系

3.外部容器通過解析配置文件,通過反射來將這些聯系在一起

 

The Hollywood principle:Don’t call us,we’ll call you.

即,所有組件都是被動的、不主動聯系(調用)外部代碼,

要等著外部代碼的調用--------所有的組件的初始化和相互調用都由容器負責實現。

簡單的說,就是整個程序之間的關系,都由容器來控制:將程序的控制權反轉給容器,就是所謂的外轉

而在我們傳統代碼中,由程序代碼直接控制


優缺點:
IoC最大的好處是什么?
    因為把對象生成放在了XML里定義,所以當我們需要換一個實現子類將會變成很簡單(一般這樣的對象都是實現于某種接口的),只要修改XML就可以了,這樣我們甚至可以實現對象的熱插拔(有點象USB接口和SCSI硬盤了)。
IoC最大的缺點是什么?
    (1)生成一個對象的步驟變復雜了(事實上操作上還是挺簡單的),對于不習慣這種方式的人,會覺得有些別扭和不直觀。
    (2)對象生成因為是使用反射編程,在效率上有些損耗。但相對于IoC提高的維護性和靈活性來說,這點損耗是微不足道的,除非某對象的生成對效率要求特別高。
    (3)缺少IDE重構操作的支持,如果在Eclipse要對類改名,那么你還需要去XML文件里手工去改了,這似乎是所有XML方式的缺憾所在。


  IOC的意思是控件反轉也就是由容器控制程序之間的關系,把控件權交給了外部容器,之前的寫法,由程序代碼直接操控,而現在控制權由應用代碼中轉到了外部容器,控制權的轉移是所謂反轉








abin 2015-04-15 13:36 發表評論
]]>
ApplicationContext的三種實現方式以及在web.xml配置的兩種方式 http://www.aygfsteel.com/stevenjohn/archive/2015/03/27/423888.htmlabinabinFri, 27 Mar 2015 06:53:00 GMThttp://www.aygfsteel.com/stevenjohn/archive/2015/03/27/423888.htmlhttp://www.aygfsteel.com/stevenjohn/comments/423888.htmlhttp://www.aygfsteel.com/stevenjohn/archive/2015/03/27/423888.html#Feedback0http://www.aygfsteel.com/stevenjohn/comments/commentRss/423888.htmlhttp://www.aygfsteel.com/stevenjohn/services/trackbacks/423888.htmlApplicationContext 是 BeanFactory 接口的子接口,它增強了 BeanFactory 的功能,處于 context 包下。很多時候, ApplicationContext 允許以聲明式方式操作容器,無須手動創建。可利用如 ContextLoader 的支持類,在 Web 應用啟動時自動創建 ApplicationContext。當然,也可以采用編程方式創建 ApplicationContext。

ApplicationContext包括BeanFactory的全部功能,因此建議優先使用ApplicationContext。除非對于某些內存非常關鍵的應用,才考慮使用 BeanFactory。

spring為ApplicationContext提供的3種實現分別為:

1、  ClassPathXmlApplicationContext:利用類路徑的XML文件來載入Bean定義的信息

[1]  ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");

[2]  String[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"};

ApplicationContext ctx = new ClassPathXmlApplication(locations);

2、 FileSystemXmlApplicationContext:利用文件系統中的XMl文件來載入Bean

定義的信息

[1]  ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml"); //加載單個配置文件

[2]  String[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"};

 ApplicationContext ctx = new FileSystemXmlApplicationContext(locations );

//加載多個配置文件

[3]  ApplicationContext ctx =new FileSystemXmlApplicationContext("D:/project/bean.xml");

//根據具體路徑加載

3、 XmlWebApplicationContext:從Web系統中的XML文件來載入Bean定義的信息。

 ServletContext servletContext = request.getSession().getServletContext();    

 ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);

 

 

配置WebApplicationContext的兩種方法:

(1)        利用Listener接口來實現

<listener>

       <listener-class>

org.springframework.web.context.ContextLoaderListener

</listener-class>

</listener>

<context-param>

       <param-name>contextConfigLocation</param-name>

       <param-value>classpath:applicationContext</param-value>

</context-param>

(2)        利用Servlet接口來實現

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:applicationContext</param-value>

</context-param>

<Servlet>

       <servlet-name>context</servlet-name>

       <servlet-class>

           org.springframework.web.context.ContextLoaderServlet

       </servlet-class>

</servlet>



abin 2015-03-27 14:53 發表評論
]]>
spring Bean 加載順序http://www.aygfsteel.com/stevenjohn/archive/2015/03/23/423763.htmlabinabinMon, 23 Mar 2015 14:10:00 GMThttp://www.aygfsteel.com/stevenjohn/archive/2015/03/23/423763.htmlhttp://www.aygfsteel.com/stevenjohn/comments/423763.htmlhttp://www.aygfsteel.com/stevenjohn/archive/2015/03/23/423763.html#Feedback0http://www.aygfsteel.com/stevenjohn/comments/commentRss/423763.htmlhttp://www.aygfsteel.com/stevenjohn/services/trackbacks/423763.html一,單一Bean

  • 裝載

1. 實例化; 
2. 設置屬性值; 
3. 如果實現了BeanNameAware接口,調用setBeanName設置Bean的ID或者Name; 
4. 如果實現BeanFactoryAware接口,調用setBeanFactory 設置BeanFactory; 
5. 如果實現ApplicationContextAware,調用setApplicationContext設置ApplicationContext 
6. 調用BeanPostProcessor的預先初始化方法; 
7. 調用InitializingBean的afterPropertiesSet()方法; 
8. 調用定制init-method方法; 
9. 調用BeanPostProcessor的后初始化方法;

  • spring容器關閉

1. 調用DisposableBean的destroy(); 
2. 調用定制的destroy-method方法;

 

二,多個Bean的先后順序

  • 優先加載BeanPostProcessor的實現Bean
  • 按Bean文件和Bean的定義順序按bean的裝載順序(即使加載多個spring文件時存在id覆蓋)
  • “設置屬性值”(第2步)時,遇到ref,則在“實例化”(第1步)之后先加載ref的id對應的bean
  • AbstractFactoryBean的子類,在第6步之后,會調用createInstance方法,之后會調用getObjectType方法
  • BeanFactoryUtils類也會改變Bean的加載順序


abin 2015-03-23 22:10 發表評論
]]>
spring BeanPostProcessorhttp://www.aygfsteel.com/stevenjohn/archive/2015/03/23/423759.htmlabinabinMon, 23 Mar 2015 11:38:00 GMThttp://www.aygfsteel.com/stevenjohn/archive/2015/03/23/423759.htmlhttp://www.aygfsteel.com/stevenjohn/comments/423759.htmlhttp://www.aygfsteel.com/stevenjohn/archive/2015/03/23/423759.html#Feedback0http://www.aygfsteel.com/stevenjohn/comments/commentRss/423759.htmlhttp://www.aygfsteel.com/stevenjohn/services/trackbacks/423759.html1、使用<context:annotation-config />簡化配置 
      Spring2.1添加了一個新的context的Schema命名空間,該命名空間對注釋驅動、屬性文件引入、加載期織入等功能提供了便捷的配置。我們知道注釋本身是不會做任何事情的,它僅提供元數據信息。要使元數據信息真正起作用,必須讓負責處理這些元數據的處理器工作起來。 
      AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor就是處理這些注釋元數據的處理器。但是直接在Spring配置文件中定義這些Bean顯得比較笨拙。Spring為我們提供了一種方便的注冊這些BeanPostProcessor的方式,這就是<context:annotation-config />:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
    <context:annotation-config />  
</beans>  

<context:annotationconfig />將隱式地向Spring容器注冊AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、 PersistenceAnnotationBeanPostProcessor以及RequiredAnnotationBeanPostProcessor這4個BeanPostProcessor。

2、使用<context:component-scan />讓Bean定義注解工作起來
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
    <context:component-scan base-package="com.kedacom.ksoa" />  
</beans>  

這里,所有通過<bean>元素定義Bean的配置內容已經被移除,僅需要添加一行<context:component-scan />配置就解決所有問題了——Spring XML配置文件得到了極致的簡化(當然配置元數據還是需要的,只不過以注釋形式存在罷了)。<context:component-scan />的base-package屬性指定了需要掃描的類包,類包及其遞歸子包中所有的類都會被處理。 
< context:component-scan />還允許定義過濾器將基包下的某些類納入或排除。Spring支持以下4種類型的過濾方式: 
過濾器類型 表達式范例 說明
注解 org.example.SomeAnnotation將所有使用SomeAnnotation注解的類過濾出來
類名指定 org.example.SomeClass過濾指定的類
正則表達式 com\.kedacom\.spring\.annotation\.web\..*通過正則表達式過濾一些類
AspectJ表達式 org.example..*Service+通過AspectJ表達式過濾一些類


以正則表達式為例,我列舉一個應用實例:
<context:component-scan base-package="com.casheen.spring.annotation">  
    <context:exclude-filter type="regex" expression="com\.casheen\.spring\.annotation\.web\..*" />  
</context:component-scan>  

值得注意的是<context:component-scan />配置項不但啟用了對類包進行掃描以實施注釋驅動Bean定義的功能,同時還啟用了注釋驅動自動注入的功能(即還隱式地在內部注冊了AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor),因此當使用<context:component-scan />后,就可以將<context:annotation-config />移除了.



abin 2015-03-23 19:38 發表評論
]]>
springMVC jstlhttp://www.aygfsteel.com/stevenjohn/archive/2013/07/26/402001.htmlabinabinFri, 26 Jul 2013 07:38:00 GMThttp://www.aygfsteel.com/stevenjohn/archive/2013/07/26/402001.htmlhttp://www.aygfsteel.com/stevenjohn/comments/402001.htmlhttp://www.aygfsteel.com/stevenjohn/archive/2013/07/26/402001.html#Feedback0http://www.aygfsteel.com/stevenjohn/comments/commentRss/402001.htmlhttp://www.aygfsteel.com/stevenjohn/services/trackbacks/402001.html//spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=" xmlns:xsi=" xmlns:context=" xmlns:mvc="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
    http://www.springframework.org/schema/util  <!-- 指定系統尋找controller路徑 -->
 <!-- json 數據格式轉換
 <mvc:annotation-driven>
  <mvc:message-converters>
   <bean id="jsonConverter" class="com.abin.lee.ssh.util.json.fastjson.FastjsonHttpMessageConverter">
    <property name="supportedMediaTypes" value="application/json" />
    <property name="serializerFeature">
     <list>
      <value>WriteMapNullValue</value>
      <value>QuoteFieldNames</value>
     </list>
    </property>
   </bean>
  </mvc:message-converters>

 </mvc:annotation-driven>
 -->
 <!-- 搜索的包路徑 -->
 <context:component-scan base-package="com.abin.lee.ssh"
  use-default-filters="false">
  <context:include-filter type="annotation"
   expression="org.springframework.stereotype.Controller" />
 </context:component-scan>
 
 <!-- jsp視圖解釋器 -->
 <bean id="jspViewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/page/" />
  <property name="suffix" value=".jsp" />
 </bean>
 
</beans>





//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="
  <display-name>front</display-name>
 
   <!-- spring MVC -->
 <servlet>
  <servlet-name>spring-mvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath*:spring-mvc.xml</param-value>
  </init-param>
  <load-on-startup>2</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>spring-mvc</servlet-name>
  <url-pattern>/mvc/*</url-pattern>
 </servlet-mapping>
 
 
 
 
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>





//UnivernalController.java

package com.abin.lee.ssh.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.abin.lee.ssh.entity.UniversalBean;
@Scope("prototype")
@Controller
@RequestMapping("/sky/")
public class UniversalController {
 
 @RequestMapping("/activity")
 public String activity(ModelMap map){
  List<UniversalBean> list=new ArrayList<UniversalBean>();
  UniversalBean bean=null;
  for(int i=0;i<=5;i++){
   bean=new UniversalBean();
   bean.setId(i);
   bean.setName("abin"+i);
   bean.setImageUrl("
http://localhost:7700/front/"+i+".jpg");
   list.add(bean);
  }
  map.put("list", list);
  return "mobile/show";
 }

}




//show.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<%@ taglib prefix="c" uri="
<%@ taglib uri="</head>

<script language="javascript" type="text/javascript" src="../script/js/share.js" ></script>
<script type="text/javascript">

</script>
<body>
 <div id="content">
  <c:forEach items="${list}" var="obj">
   <div id="" class="lb">
    <c:choose>
     <c:when test="${empty obj.name}">
      I am Empty
     </c:when>
     <c:when test="${obj.name=='abin1'}">
      ${obj.name} is a boy
     </c:when>
     <c:otherwise>
      ${obj.name } is normally
     </c:otherwise>
    </c:choose>
    <img alt="顯示不出來" src="${obj.imageUrl }"></img>
   </div>
  
  </c:forEach>
 </div>
</body>
</html>





















abin 2013-07-26 15:38 發表評論
]]>
spring 常見要點http://www.aygfsteel.com/stevenjohn/archive/2013/05/29/399919.htmlabinabinWed, 29 May 2013 06:37:00 GMThttp://www.aygfsteel.com/stevenjohn/archive/2013/05/29/399919.htmlhttp://www.aygfsteel.com/stevenjohn/comments/399919.htmlhttp://www.aygfsteel.com/stevenjohn/archive/2013/05/29/399919.html#Feedback0http://www.aygfsteel.com/stevenjohn/comments/commentRss/399919.htmlhttp://www.aygfsteel.com/stevenjohn/services/trackbacks/399919.htmlAOP有三種植入切面的方法:其一是編譯期織入,這要求使用特殊的Java編譯器,AspectJ是其中的代表者;其二是類裝載期織入,而這要求使用特殊的類裝載器,AspectJ和AspectWerkz是其中的代表者;其三為動態代理織入,在運行期為目標類添加增強生成子類的方式,Spring AOP采用動態代理織入切面。

Spring AOP使用了兩種代理機制,一種是基于JDK的動態代理,另一種是基于CGLib的動態代理,之所以需要兩種代理機制,很大程度上是因為JDK本身只提供基于接口的代理,不支持類的代理。

Spring的三種注入方式:
接口注入(不推薦)
getter,setter方式注入(比較常用)
構造器注入(死的應用)

什么是AOP?
面向切面編程(AOP)完善spring的依賴注入(DI),面向切面編程在spring中主要表現為兩個方面
1.面向切面編程提供聲明式事務管理
2.spring支持用戶自定義的切面

面向切面編程(aop)是對面向對象編程(oop)的補充,
面向對象編程將程序分解成各個層次的對象,面向切面編程將程序運行過程分解成各個切面。
AOP從程序運行角度考慮程序的結構,提取業務處理過程的切面,oop是靜態的抽象,aop是動態的抽象,
是對應用執行過程中的步驟進行抽象,,從而獲得步驟之間的邏輯劃分。

aop框架具有的兩個特征:
1.各個步驟之間的良好隔離性
2.源代碼無關性

什么是DI機制?
依賴注入(Dependecy Injection)和控制反轉(Inversion of Control)是同一個概念,具體的講:當某個角色
需要另外一個角色協助的時候,在傳統的程序設計過程中,通常由調用者來創建被調用者的實例。但在spring中
創建被調用者的工作不再由調用者來完成,因此稱為控制反轉。創建被調用者的工作由spring來完成,然后注入調用者
因此也稱為依賴注入。
spring以動態靈活的方式來管理對象 , 注入的兩種方式,設置注入和構造注入。
設置注入的優點:直觀,自然
構造注入的優點:可以在構造器中決定依賴關系的順序。

spring 的優點都有哪些?
1.降低了組件之間的耦合性 ,實現了軟件各層之間的解耦
2.可以使用容易提供的眾多服務,如事務管理,消息服務等
3.容器提供單例模式支持
4.容器提供了AOP技術,利用它很容易實現如權限攔截,運行期監控等功能
5.容器提供了眾多的輔助類,能加快應用的開發
6.spring對于主流的應用框架提供了集成支持,如hibernate,JPA,Struts等
7.spring屬于低侵入式設計,代碼的污染極低
8.獨立于各種應用服務器
9.spring的DI機制降低了業務對象替換的復雜性
10.Spring的高度開放性,并不強制應用完全依賴于Spring,開發者可以自由選擇spring的部分或全部


一、spring工作原理:

1.spring mvc請所有的請求都提交給DispatcherServlet,它會委托應用系統的其他模塊負責負責對請求進行真正的處理工作。
2.DispatcherServlet查詢一個或多個HandlerMapping,找到處理請求的Controller.
3.DispatcherServlet請請求提交到目標Controller
4.Controller進行業務邏輯處理后,會返回一個ModelAndView
5.Dispathcher查詢一個或多個ViewResolver視圖解析器,找到ModelAndView對象指定的視圖對象
6.視圖對象負責渲染返回給客戶端。


描述一下Spring中實現DI(Dependency Injection)的幾種方式

方式一:接口注入,在實際中得到了普遍應用,即使在IOC的概念尚未確立時,這樣的方法也已經頻繁出現在我們的代碼中。
方式二:Type2 IoC: Setter injection對象創建之后,將被依賴對象通過set方法設置進去
方式三:Type3 IoC: Constructor injection對象創建時,被依賴對象以構造方法參數的方式注入

 簡單描述下IOC(inversion of control)的理解
一個類需要用到某個接口的方法,我們需要將類A和接口B的實現關聯起來,最簡單的方法是類A中創建一個對于接口B的實現C的實例,但這種方法顯然兩者的依賴(Dependency)太大了。而IoC的方法是只在類A中定義好用于關聯接口B的實現的方法,將類A,接口B和接口B的實現C放入IoC的 容器(Container)中,通過一定的配置由容器(Container)來實現類A與接口B的實現C的關聯。

spring提供的事務管理可以分為兩類:編程式的和聲明式的。編程式的,比較靈活,但是代碼量大,存在重復的代碼比較多;聲明式的比編程式的更靈活。
編程式主要使用transactionTemplate。省略了部分的提交,回滾,一系列的事務對象定義,需注入事務管理對象.
void add()
{
transactionTemplate.execute( new TransactionCallback(){
pulic Object doInTransaction(TransactionStatus ts)
{ //do sth}
}
}
聲明式:
使用TransactionProxyFactoryBean:

PROPAGATION_REQUIRED PROPAGATION_REQUIRED PROPAGATION_REQUIRED,readOnly
圍繞Poxy的動態代理 能夠自動的提交和回滾事務
org.springframework.transaction.interceptor.TransactionProxyFactoryBean
PROPAGATION_REQUIRED–支持當前事務,如果當前沒有事務,就新建一個事務。這是最常見的選擇。
PROPAGATION_SUPPORTS–支持當前事務,如果當前沒有事務,就以非事務方式執行。
PROPAGATION_MANDATORY–支持當前事務,如果當前沒有事務,就拋出異常。
PROPAGATION_REQUIRES_NEW–新建事務,如果當前存在事務,把當前事務掛起。
PROPAGATION_NOT_SUPPORTED–以非事務方式執行操作,如果當前存在事務,就把當前事務掛起。
PROPAGATION_NEVER–以非事務方式執行,如果當前存在事務,則拋出異常。
PROPAGATION_NESTED–如果當前存在事務,則在嵌套事務內執行。如果當前沒有事務,則進行與PROPAGATION_REQUIRED類似的操作。

spring中的核心類有那些,各有什么作用?
BeanFactory:產生一個新的實例,可以實現單例模式
BeanWrapper:提供統一的get及set方法
ApplicationContext:提供框架的實現,包括BeanFactory的所有功能
spring的ioc及di代表什么意思?
控制權由代碼轉向容器,通過容器動態將某些對象加入。
如何在spring中實現國際化?
在applicationContext.xml加載一個bean
message.properties是一個鍵名加鍵值的文件,

















































 



abin 2013-05-29 14:37 發表評論
]]>
SpringMVC Spring3 Hibernate3.3全注解http://www.aygfsteel.com/stevenjohn/archive/2012/10/21/389952.htmlabinabinSat, 20 Oct 2012 17:12:00 GMThttp://www.aygfsteel.com/stevenjohn/archive/2012/10/21/389952.htmlhttp://www.aygfsteel.com/stevenjohn/comments/389952.htmlhttp://www.aygfsteel.com/stevenjohn/archive/2012/10/21/389952.html#Feedback1http://www.aygfsteel.com/stevenjohn/comments/commentRss/389952.htmlhttp://www.aygfsteel.com/stevenjohn/services/trackbacks/389952.html//web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=" xmlns="http://java.sun.com/xml/ns/javaee  id="WebApp_ID" version="3.0">
 <display-name>universal</display-name>
 <!-- spring -->
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath*:com/abin/lee/ssh/spring-service.xml</param-value>
 </context-param>
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>


 <!-- spring MVC -->
 <servlet>
  <servlet-name>spring-mvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath*:com/abin/lee/ssh/spring-mvc.xml</param-value>
  </init-param>
  <load-on-startup>2</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>spring-mvc</servlet-name>
  <url-pattern>/mvc/*</url-pattern>
 </servlet-mapping>
 <!-- spring encoding -->
 <filter>
  <filter-name>utf8-encoding</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>utf-8</param-value>
  </init-param>
  <init-param>
   <param-name>forceEncoding</param-name>
   <param-value>true</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>utf8-encoding</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

 


 <welcome-file-list>
  <welcome-file>index.html</welcome-file>
  <welcome-file>index.htm</welcome-file>
  <welcome-file>index.jsp</welcome-file>
  <welcome-file>default.html</welcome-file>
  <welcome-file>default.htm</welcome-file>
  <welcome-file>default.jsp</welcome-file>
 </welcome-file-list>
</web-app>





//spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="
 xmlns:xsi=" xmlns:context=" xmlns:mvc="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
    http://www.springframework.org/schema/util  <!-- 指定系統尋找controller路徑 -->
 <mvc:annotation-driven>
  <!-- json 數據格式轉換-->
  <mvc:message-converters>
   <bean class="com.abin.lee.ssh.function.FastJsonAbstractHttpMessageConverter">
    <property name="supportedMediaTypes" value="application/json" />
    <property name="serializerFeature">
     <list>
      <value>WriteMapNullValue</value>
      <value>QuoteFieldNames</value>
     </list>
    </property>
   </bean>
  </mvc:message-converters>

 </mvc:annotation-driven>
 <!-- 搜索的包路徑 -->
 <context:component-scan base-package="com.abin.lee.ssh"
  use-default-filters="false">
  <context:include-filter type="annotation"
   expression="org.springframework.stereotype.Controller" />
 </context:component-scan>

</beans>





//spring-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="
 xmlns:xsi=" xmlns:context=" xmlns:jdbc="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 
    http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd 
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd 
    http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd 
   http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd 
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd 
   http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd 
  http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd 
    http://www.springframework.org/schema/util  
 <context:annotation-config />
 <context:component-scan base-package="com.abin.lee.ssh"></context:component-scan>
 
 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"       
        destroy-method="close">      
    <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>      
    <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:xe"/>      
    <property name="user" value="abin"/>      
    <property name="password" value="abin"/>      
 </bean>
 
 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource">
   <ref bean="dataSource" />
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">
     org.hibernate.dialect.OracleDialect
    </prop>
    <prop key="hibernate.show_sql">
     true
    </prop>
    <prop key="hibernate.show_sql">true</prop>
    <prop key="hibernate.format_sql">true</prop>
    <prop key="hibernate.hbm2ddl.auto">update</prop>
   </props>
  </property>
  <!--主鍵Bean類
  <property name="annotatedClasses">
   <list>
    <value>com.abin.lee.ssh.entity.ModeBean</value>
   </list>
  </property>
   -->
  <!-- 自動掃描-->
   <property name="packagesToScan" value="com.abin.lee.ssh.entity" />
 </bean>
 
 <!-- 配置事務管理器 -->
 <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory">
   <ref bean="sessionFactory" />
  </property>
 </bean>
 
 <!-- 配置注解實現管理事務(cglib:proxy-target-class="true") -->
 <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
 <!-- 指定使用cglib -->
 <!--   -->
 <aop:aspectj-autoproxy proxy-target-class="true" />
 
 <!-- 配置事務的傳播特性 -->
 <tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
   <tx:method name="save*" propagation="REQUIRED" />
   <tx:method name="insert*" propagation="REQUIRED" />
   <tx:method name="update*" propagation="REQUIRED" />
   <tx:method name="delete*" propagation="REQUIRED" />
   <tx:method name="*" read-only="false" />
  </tx:attributes>
 </tx:advice>
 
 <!-- 那些類的哪些方法參與事務-->
 <aop:config>
  <aop:pointcut id="allServiceMethod" expression="execution(* com.abin.lee.ssh.spring.*.*(..))" />
  <aop:advisor pointcut-ref="allServiceMethod" advice-ref="txAdvice" />
 </aop:config>
 
</beans>



//FastJsonAbstractHttpMessageConverter.java

package com.abin.lee.ssh.function;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.nio.charset.Charset;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.FileCopyUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

//來對requestbody 或responsebody中的數據進行解析
public class FastJsonAbstractHttpMessageConverter extends AbstractHttpMessageConverter<Object>{
  public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
 // fastjson特性參數 
    private SerializerFeature[] serializerFeature; 
 
    public SerializerFeature[] getSerializerFeature() { 
        return serializerFeature; 
    } 
 
    public void setSerializerFeature(SerializerFeature[] serializerFeature) { 
        this.serializerFeature = serializerFeature; 
    } 
 
 //限定頁面文本傳送類型 只有數據是改類型 的 才會進行攔截
 //application/json
 public FastJsonAbstractHttpMessageConverter(){
//  super(new MediaType("text","plain"));
  super(new MediaType("application","json"));
 }
 @Override
 protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputmessage) throws IOException,
   HttpMessageNotReadableException {
  Charset charset;
  MediaType mediaType=inputmessage.getHeaders().getContentType();
  if(mediaType!=null&&mediaType.getCharSet()!=null){
   charset=mediaType.getCharSet();
  }else{
   charset=Charset.forName("UTF-8");
  }
  
  String input=FileCopyUtils.copyToString(new InputStreamReader(inputmessage.getBody(),charset));
  String result=URLDecoder.decode(input, "UTF-8");
  System.out.println(result);
  /*OrgnizationPO po=new OrgnizationPO();
  po.setId(1);
  po.setName("11");
  po.setOrgdesc("1");*/
  
  /*ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
        int i; 
        while ((i = inputmessage.getBody().read()) != -1) { 
            baos.write(i); 
        }  */
        return JSON.parseObject(result, clazz);
//        return JSON.parseArray(baos.toString(), clazz);
//  return po;
 }

 @Override
 protected boolean supports(Class<?> clazz) {
  return true;
  //throw new UnsupportedOperationException();
 }

 @Override
 protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException,
   HttpMessageNotWritableException {
  String jsonString = JSON.toJSONString(o, serializerFeature); 
//  System.out.println(jsonString);
        OutputStream out = outputMessage.getBody(); 
        out.write(jsonString.getBytes(DEFAULT_CHARSET)); 
        out.flush(); 
 }

}






package com.abin.lee.ssh.hibernate;

import com.abin.lee.ssh.entity.ModeBean;

public interface ModeDao {
 public boolean insert(ModeBean mode);
}




package com.abin.lee.ssh.hibernate.impl;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.abin.lee.ssh.entity.ModeBean;
import com.abin.lee.ssh.hibernate.ModeDao;
@Repository
public class ModeDaoImpl extends HibernateDaoSupport implements ModeDao{
 
 @Resource(name = "sessionFactory")
 public void setSuperSessionFactory(SessionFactory sessionFactory) {
  super.setSessionFactory(sessionFactory);
 }
 
 public boolean insert(ModeBean mode) {
  boolean flag=false;
  try {
   this.getHibernateTemplate().saveOrUpdate(mode);
   flag=true;
  } catch (Exception e) {
   e.printStackTrace();
  }
  return flag;
 }
 
 
}






package com.abin.lee.ssh.spring;

import com.abin.lee.ssh.entity.ModeBean;

public interface ModeService {
 public boolean insert(ModeBean mode);

}





package com.abin.lee.ssh.spring.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.abin.lee.ssh.entity.ModeBean;
import com.abin.lee.ssh.hibernate.ModeDao;
import com.abin.lee.ssh.spring.ModeService;

@Service
@Transactional(readOnly = true, timeout = 2, propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
public class ModeServiceImpl implements ModeService {
 @Resource
 private ModeDao modeDao;

 @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
 public boolean insert(ModeBean mode) {
  boolean flag = false;
  try {
   flag = this.modeDao.insert(mode);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return flag;
 }

}






package com.abin.lee.ssh.springmvc;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.abin.lee.ssh.dto.request.ModeRequest;
import com.abin.lee.ssh.dto.response.ModeResponse;
import com.abin.lee.ssh.entity.ModeBean;
import com.abin.lee.ssh.spring.ModeService;

@Controller
@RequestMapping("/stevenjohn/")
public class ModeController {
 @Resource
 private ModeService modeService;

 @RequestMapping(value = "getMode", method = RequestMethod.POST)
 public @ResponseBody
 ModeResponse getMode(
   @ModelAttribute ModeRequest modeRequest) {
  ModeResponse response = new ModeResponse();
  String id=modeRequest.getId();
  String username=modeRequest.getUsername();
  String password=modeRequest.getPassword();
  int age=modeRequest.getAge();
  String address=modeRequest.getAddress();
  String email=modeRequest.getEmail();
  ModeBean mode=new ModeBean(id, username, password, age, address, email);
  boolean flag=modeService.insert(mode);
  System.out.println("flag="+flag);
  if(flag==true){
   response.setStatus("success");
  }else{
   response.setStatus("failure");
  }
  
  return response;
 }
}




package com.abin.lee.ssh.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="MODEBEAN")
public class ModeBean implements Serializable{
 @Id
 @Column(name="ID")
 private String id;
 @Column(name="USERNAME",length=100,nullable=true)
 private String username;
 @Column(name="PASSWORD",length=100,nullable=true)
 private String password;
 @Column(name="AGE",length=10,nullable=true)
 private int age;
 @Column(name="ADDRESS",length=100,nullable=true)
 private String address;
 @Column(name="EMAIL",length=100,nullable=true)
 private String email;
 public ModeBean() {
 }
 public ModeBean(String id, String username, String password, int age,
   String address, String email) {
  super();
  this.id = id;
  this.username = username;
  this.password = password;
  this.age = age;
  this.address = address;
  this.email = email;
 }
 
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
 
 
}







//SpringMVC請求參數

package com.abin.lee.ssh.dto.request;

import java.io.Serializable;

public class ModeRequest implements Serializable{
 /**
  *
  */
 private static final long serialVersionUID = 1886596479119297989L;
 private String id;
 private String username;
 private String password;
 private int age;
 private String address;
 private String email;
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
 
}





//SpringMVC響應參數


package com.abin.lee.ssh.dto.response;

import java.io.Serializable;

public class ModeResponse implements Serializable{
 /**
  *
  */
 private static final long serialVersionUID = 7725619232731203410L;
 private String status;
 private String message;
 public ModeResponse() {
 }
 public ModeResponse(String status, String message) {
  super();
  this.status = status;
  this.message = message;
 }
 public String getStatus() {
  return status;
 }
 public void setStatus(String status) {
  this.status = status;
 }
 public String getMessage() {
  return message;
 }
 public void setMessage(String message) {
  this.message = message;
 }
 
}




//log4j.properties

log4j.rootCategory=info,log,console

log4j.logger.org.apache.axis2.enterprise=FATAL
log4j.logger.de.hunsicker.jalopy.io=FATAL
log4j.logger.httpclient.wire.header=FATAL
log4j.logger.org.apache.commons.httpclient=FATAL

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d [%t] %-5p %c %x - %m%n
 
log4j.appender.log=org.apache.log4j.DailyRollingFileAppender
log4j.appender.log.File=../logs/mms.log
log4j.appender.log.layout=org.apache.log4j.PatternLayout
log4j.appender.log.layout.ConversionPattern=%d [%t] %-5p %c %x - %m%n








//測試springMVC的Junit4+httpClient類:

package com.abin.lee.ssm;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import junit.framework.TestCase;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.junit.Test;

public class HttpsClient extends TestCase {
 private String httpUrl = "
http://localhost:7000/universal/mvc/stevenjohn/getMode";

 @Test
 public void testHttpsClient() {
  try {
   HttpClient httpClient = new DefaultHttpClient();
   HttpPost httpPost = new HttpPost(httpUrl);
   List<NameValuePair> nvps = new ArrayList<NameValuePair>();
   nvps.add(new BasicNameValuePair("id", UUID.randomUUID().toString()));
   nvps.add(new BasicNameValuePair("username", "abin"));
   nvps.add(new BasicNameValuePair("password", "abing"));
   nvps.add(new BasicNameValuePair("age", "28"));
   nvps.add(new BasicNameValuePair("address", "beijing of china"));
   nvps.add(new BasicNameValuePair("email", "varyall@tom.com"));
   httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
   HttpResponse httpResponse = httpClient.execute(httpPost);
   BufferedReader buffer = new BufferedReader(new InputStreamReader(
     httpResponse.getEntity().getContent()));
   StringBuffer stb=new StringBuffer();
   String line=null;
   while((line=buffer.readLine())!=null){
    stb.append(line);
   }
   buffer.close();
   String result=stb.toString();
   System.out.println("result="+result);
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

}



abin 2012-10-21 01:12 發表評論
]]>
cxf spring集成(二)http://www.aygfsteel.com/stevenjohn/archive/2012/08/21/385926.htmlabinabinTue, 21 Aug 2012 03:17:00 GMThttp://www.aygfsteel.com/stevenjohn/archive/2012/08/21/385926.htmlhttp://www.aygfsteel.com/stevenjohn/comments/385926.htmlhttp://www.aygfsteel.com/stevenjohn/archive/2012/08/21/385926.html#Feedback0http://www.aygfsteel.com/stevenjohn/comments/commentRss/385926.htmlhttp://www.aygfsteel.com/stevenjohn/services/trackbacks/385926.html五、CXF WebService整合Spring

首先,CXF和spring整合需要準備如下jar包文件:

image

這邊我是用Spring的jar包是Spring官方提供的,并沒有使用CXF中的Spring的jar文件。

添加這么多文件后,首先在web.xml中添加如下配置:

<!-- 加載Spring容器配置 -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 設置Spring容器加載配置文件路徑 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext-server.xml</param-value>
</context-param>
 
<listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
 
<servlet>
    <servlet-name>CXFService</servlet-name>
    <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet>
 
<servlet-mapping>
    <servlet-name>CXFService</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

然后在src目錄中,新建一個applicationContext-server.xml文件,文件內容如下:

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans >
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://cxf.apache.org/jaxws 
    http://cxf.apache.org/schemas/jaxws.xsd"

注意上面的帶下劃線加粗部分,這個很重要的哦!不能寫錯或是遺漏了。

添加完這個文件后,還需要在這個文件中導入這么幾個文件。文件內容如下:

<import resource="classpath:META-INF/cxf/cxf.xml"/>
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>

下面開始寫服務器端代碼,首先定制服務器端的接口,代碼如下:

package com.hoo.service;
 
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import com.hoo.entity.User;
import com.hoo.entity.Users;
 
/**
 * <b>function:</b>定制客戶端請求WebService所需要的接口
 * @author hoojo
 * @createDate 2011-3-18 上午08:22:55
 * @file ComplexUserService.java
 * @package com.hoo.service
 * @project CXFWebService
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
@WebService
@SOAPBinding(style = Style.RPC)
public interface IComplexUserService {
    
    public User getUserByName(@WebParam(name = "name") String name);
    
    public void setUser(User user);
}

下面編寫WebService的實現類,服務器端實現代碼如下:

package com.hoo.service;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import com.hoo.entity.User;
import com.hoo.entity.Users;
 
/**
 * <b>function:</b> WebService傳遞復雜對象,如JavaBean、Array、List、Map等
 * @author hoojo
 * @createDate 2011-3-18 上午08:22:55
 * @file ComplexUserService.java
 * @package com.hoo.service
 * @project CXFWebService
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
@WebService
@SOAPBinding(style = Style.RPC)
@SuppressWarnings("deprecation")
public class ComplexUserService implements IComplexUserService {
    
    public User getUserByName(@WebParam(name = "name") String name) {
        User user = new User();
        user.setId(new Date().getSeconds());
        user.setName(name);
        user.setAddress("china");
        user.setEmail(name + "@hoo.com");
        return user;
    }
    
    public void setUser(User user) {
        System.out.println("############Server setUser###########");
        System.out.println("setUser:" + user);
    }
}

注意的是和Spring集成,這里一定要完成接口實現,如果沒有接口的話會有錯誤的。

下面要在applicationContext-server.xml文件中添加如下配置:

<bean id="userServiceBean" class="com.hoo.service.ComplexUserService"/>
 
<bean id="inMessageInterceptor" class="com.hoo.interceptor.MessageInterceptor">
    <constructor-arg  value="receive"/>
</bean>
 
<bean id="outLoggingInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>
<!-- 注意下面的address,這里的address的名稱就是訪問的WebService的name -->
<jaxws:server id="userService" serviceClass="com.hoo.service.IComplexUserService" address="/Users">
    <jaxws:serviceBean>
        <!-- 要暴露的 bean 的引用 -->
        <ref bean="userServiceBean"/>
    </jaxws:serviceBean>
    <jaxws:inInterceptors>
        <ref bean="inMessageInterceptor"/>
    </jaxws:inInterceptors>
    <jaxws:outInterceptors>
        <ref bean="outLoggingInterceptor"/>
    </jaxws:outInterceptors>
</jaxws:server>

下面啟動tomcat服務器后,在WebBrowser中請求:

http://localhost:8080/CXFWebService/Users?wsdl

如果你能看到wsdl的xml文件的內容,就說明你成功了,注意的是上面地址的Users就是上面xml配置中的address的名稱,是一一對應的。

下面編寫客戶端請求的代碼,代碼如下:

package com.hoo.client;
 
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import com.hoo.entity.User;
import com.hoo.service.IComplexUserService;
 
/**
 * <b>function:</b>請求Spring整合CXF的WebService客戶端
 * @author hoojo
 * @createDate 2011-3-28 下午03:20:35
 * @file SpringUsersWsClient.java
 * @package com.hoo.client
 * @project CXFWebService
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public class SpringUsersWsClient {
 
    public static void main(String[] args) {
        //調用WebService
        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.setServiceClass(IComplexUserService.class);
        factory.setAddress("http://localhost:8080/CXFWebService/Users");
        
        IComplexUserService service = (IComplexUserService) factory.create();
        
        System.out.println("#############Client getUserByName##############");
        User user = service.getUserByName("hoojo");
        System.out.println(user);
        
        user.setAddress("China-Guangzhou");
        service.setUser(user);
    }
}

運行后,可以在控制臺中看到

log4j:WARN No appenders could be found for logger (org.apache.cxf.bus.spring.BusApplicationContext).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
2011-3-28 18:12:26 org.apache.cxf.service.factory.ReflectionServiceFactoryBean buildServiceFromClass
信息: Creating Service {http://service.hoo.com/}IComplexUserServiceService from class com.hoo.service.IComplexUserService
#############Client getUserByName##############
27#hoojo#hoojo@hoo.com#china

Tomcat控制臺
 image 

這個server端是通過Spring整合配置的,下面我們將Client端也通過Spring配置完成整合。

首先增加applicationContext-client.xml配置文件,文件內容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans >
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://cxf.apache.org/jaxws 
    http://cxf.apache.org/schemas/jaxws.xsd"
    
    <import resource="classpath:META-INF/cxf/cxf.xml"/>
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
    
    <jaxws:client id="userWsClient" serviceClass="com.hoo.service.IComplexUserService" 
        address="http://localhost:8080/CXFWebService/Users"/>
</beans>

客戶端請求代碼如下:

package com.hoo.client;
 
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.hoo.entity.User;
import com.hoo.service.IComplexUserService;
 
/**
 * <b>function:</b>請求Spring整合CXF的WebService客戶端
 * @author hoojo
 * @createDate 2011-3-28 下午03:20:35
 * @file SpringUsersWsClient.java
 * @package com.hoo.client
 * @project CXFWebService
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public class SpringUsersWsClient {
 
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-client.xml");
        
        IComplexUserService service = ctx.getBean("userWsClient", IComplexUserService.class);
        
        System.out.println("#############Client getUserByName##############");
        User user = service.getUserByName("hoojo");
        System.out.println(user);
        
        user.setAddress("China-Guangzhou");
        service.setUser(user);
    }
}

運行后結果如下:

#############Client getUserByName##############
45#hoojo#hoojo@hoo.com#china
############Server setUser###########
setUser:45#hoojo#hoojo@hoo.com#China-Guangzhou

作者:hoojo
出處:

http://www.cnblogs.com/hoojo/archive/2011/03/30/1999563.html
blog:http://blog.csdn.net/IBM_hoojo
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。

 


版權所有,轉載請注明出處 本文出自: http://www.cnblogs.com/hoojo/archive/2011/03/30/1999563.html


abin 2012-08-21 11:17 發表評論
]]>
cxf spring集成(一)http://www.aygfsteel.com/stevenjohn/archive/2012/08/21/385896.htmlabinabinMon, 20 Aug 2012 16:27:00 GMThttp://www.aygfsteel.com/stevenjohn/archive/2012/08/21/385896.htmlhttp://www.aygfsteel.com/stevenjohn/comments/385896.htmlhttp://www.aygfsteel.com/stevenjohn/archive/2012/08/21/385896.html#Feedback0http://www.aygfsteel.com/stevenjohn/comments/commentRss/385896.htmlhttp://www.aygfsteel.com/stevenjohn/services/trackbacks/385896.html/**
 *
 */
package com.abin.lee.cxf;

import javax.jws.WebService;

/**
 * @author abin
 *
 */
@WebService(targetNamespace="cxf.lee.abin.com")
public interface IUserService {
 public String getMessage(String message);
}





package com.abin.lee.cxf;

import javax.jws.WebService;

@WebService(endpointInterface="com.abin.lee.cxf.IUserService")
public class UserService implements IUserService{

 public String getMessage(String message) {
  return message+" welcome to beijing";
 }
 
}






<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=" xmlns:xsi=" xmlns:tx=" xmlns:jaxws=" xmlns:cxf=" xmlns:wsa=" xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-beans-3.0.xsd
 http://cxf.apache.org/core
 http://cxf.apache.org/schemas/core.xsd
 http://cxf.apache.org/jaxws
 http://cxf.apache.org/schemas/jaxws.xsd
 http://www.springframework.org/schema/aop
 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
 http://www.springframework.org/schema/context
  <import resource="classpath:META-INF/cxf/cxf.xml" />
 <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
 <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
 
 <cxf:bus>
  <cxf:features>
   <!--日志攔截功能,用于監控soap內容,開發后可以刪除 -->
   <cxf:logging/>
   <wsa:addressing/>
  </cxf:features>
 </cxf:bus> 

 <bean id="userService" class="com.abin.lee.cxf.UserService"></bean>
 <jaxws:endpoint id="userWebservice" implementor="#userService" address="/UserService" publish="true" />


</beans>

 





<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
   <!--
     classpath*:com/abin/lee/spring/queue/applicationContext-springqueue.xml,
     classpath*:com/abin/lee/quartz/applicationContext-quartzCluster.xml,
     classpath*:com/abin/lee/quartz/applicationContext-quartzHeartCluster.xml,
     classpath*:com/abin/lee/quartz/applicationContext-activemq.xml
   -->
   classpath*:com/abin/lee/cxf/applicationContext-cxf.xml
  </param-value>
 </context-param>
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <!--cxf服務啟動servlet-->
 <servlet>   
  <servlet-name>CXFServlet</servlet-name>   
  <servlet-class>   
            org.apache.cxf.transport.servlet.CXFServlet    
  </servlet-class>   
  <load-on-startup>1</load-on-startup>   
 </servlet>   
 <servlet-mapping>   
  <servlet-name>CXFServlet</servlet-name>   
  <url-pattern>/service/*</url-pattern>   
 </servlet-mapping> 






package com.abin.lee.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * 獲取spring容器,以訪問容器中定義的其他bean
 *
 * @author lyltiger
 * @since MOSTsView 3.0 2009-11-16
 */
public class SpringContextUtil implements ApplicationContextAware {

 // Spring應用上下文環境
 private static ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
   "com/abin/lee/cxf/applicationContext-cxf.xml");

 /**
  * 實現ApplicationContextAware接口的回調方法,設置上下文環境
  *
  * @param applicationContext
  */
 public void setApplicationContext(ApplicationContext applicationContext) {
  SpringContextUtil.applicationContext = applicationContext;
 }

 /**
  * @return ApplicationContext
  */
 public static ApplicationContext getApplicationContext() {
  return applicationContext;
 }

 /**
  * 獲取對象 這里重寫了bean方法,起主要作用
  *
  * @param name
  * @return Object 一個以所給名字注冊的bean的實例
  * @throws BeansException
  */
 public static Object getBean(String name) throws BeansException {
  return applicationContext.getBean(name);
 }

}









package com.abin.lee.cxf.test;

import com.abin.lee.cxf.UserService;
import com.abin.lee.spring.SpringContextUtil;

import junit.framework.TestCase;

public class TestUserService extends TestCase{
 public void testcxf(){
  UserService userService=(UserService)SpringContextUtil.getBean("userService");
  
  String response=userService.getMessage("abin");
  System.out.println("response="+response);
  System.exit(0);
 }
}




abin 2012-08-21 00:27 發表評論
]]>
采用Spring管理Bean和依賴注入 http://www.aygfsteel.com/stevenjohn/archive/2012/08/20/385846.htmlabinabinMon, 20 Aug 2012 04:34:00 GMThttp://www.aygfsteel.com/stevenjohn/archive/2012/08/20/385846.htmlhttp://www.aygfsteel.com/stevenjohn/comments/385846.htmlhttp://www.aygfsteel.com/stevenjohn/archive/2012/08/20/385846.html#Feedback0http://www.aygfsteel.com/stevenjohn/comments/commentRss/385846.htmlhttp://www.aygfsteel.com/stevenjohn/services/trackbacks/385846.html閱讀全文

abin 2012-08-20 12:34 發表評論
]]>
Spring獲取bean實例http://www.aygfsteel.com/stevenjohn/archive/2012/08/20/385823.htmlabinabinMon, 20 Aug 2012 03:34:00 GMThttp://www.aygfsteel.com/stevenjohn/archive/2012/08/20/385823.htmlhttp://www.aygfsteel.com/stevenjohn/comments/385823.htmlhttp://www.aygfsteel.com/stevenjohn/archive/2012/08/20/385823.html#Feedback0http://www.aygfsteel.com/stevenjohn/comments/commentRss/385823.htmlhttp://www.aygfsteel.com/stevenjohn/services/trackbacks/385823.html方法一:
package com.abin.lee.queue;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * 獲取spring容器,以訪問容器中定義的其他bean
 *
 * @author lyltiger
 * @since MOSTsView 3.0 2009-11-16
 */
public class SpringContextUtil implements ApplicationContextAware {

 // Spring應用上下文環境
 private static ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
   "com/abin/lee/spring/applicationContext-queue.xml");

 /**
  * 實現ApplicationContextAware接口的回調方法,設置上下文環境
  *
  * @param applicationContext
  */
 public void setApplicationContext(ApplicationContext applicationContext) {
  SpringContextUtil.applicationContext = applicationContext;
 }

 /**
  * @return ApplicationContext
  */
 public static ApplicationContext getApplicationContext() {
  return applicationContext;
 }

 /**
  * 獲取對象 這里重寫了bean方法,起主要作用
  *
  * @param name
  * @return Object 一個以所給名字注冊的bean的實例
  * @throws BeansException
  */
 public static Object getBean(String name) throws BeansException {
  return applicationContext.getBean(name);
 }

}





方法二:

package com.abin.lee.queue;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class BeanFactoryUtil {
 private static BeanFactory factory = new XmlBeanFactory(
   new ClassPathResource(
     "com/abin/lee/spring/applicationContext-queue.xml"));

 public static BeanFactory getFactory() {
  return factory;
 }

 public static void setFactory(BeanFactory factory) {
  BeanFactoryUtil.factory = factory;
 }
 
 public static Object getBean(String name){
  return factory.getBean(name);
 }
}







具體用法:

package com.abin.lee.queue;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class QueueServlet extends HttpServlet{
 
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  Map map=request.getParameterMap();
  String name1=(String)((Object[])map.get("name1"))[0];
  String name2=(String)((Object[])map.get("name2"))[0];
  MakeQueue makeQueue = (MakeQueue)BeanFactoryUtil.getBean("makeQueue");//bean的名稱
  System.out.println(makeQueue.queueSize());
  makeQueue.addQueue(name1);
  makeQueue.addQueue(name2);
  System.out.println(makeQueue.queueSize());
  
  ServletOutputStream out=response.getOutputStream();
  BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out));
  writer.write("success");
  writer.flush();
  writer.close();
 }
}





abin 2012-08-20 11:34 發表評論
]]>
Spring:JdbcTemplate使用指南http://www.aygfsteel.com/stevenjohn/archive/2012/06/25/381407.htmlabinabinMon, 25 Jun 2012 02:28:00 GMThttp://www.aygfsteel.com/stevenjohn/archive/2012/06/25/381407.htmlhttp://www.aygfsteel.com/stevenjohn/comments/381407.htmlhttp://www.aygfsteel.com/stevenjohn/archive/2012/06/25/381407.html#Feedback0http://www.aygfsteel.com/stevenjohn/comments/commentRss/381407.htmlhttp://www.aygfsteel.com/stevenjohn/services/trackbacks/381407.html閱讀全文

abin 2012-06-25 10:28 發表評論
]]>
主站蜘蛛池模板: 贵港市| 株洲市| 突泉县| 温宿县| 视频| 荣成市| 馆陶县| 蒙自县| 新安县| 临安市| 富民县| 连城县| 台江县| 连山| 东阳市| 桑植县| 皋兰县| 琼中| 漠河县| 全南县| 京山县| 云安县| 德格县| 德昌县| 城固县| 屏东市| 白朗县| 湄潭县| 尼玛县| 青川县| 获嘉县| 朝阳县| 平山县| 新竹市| 淮滨县| 塘沽区| 娄底市| 宜兰市| 武陟县| 庄浪县| 六安市|