標籤:spring iocdi 依賴注入 控制反轉 ssh註解
巴巴運動網-整合hibernate4+spring4(3)使用註解
1、項目圖解
2、首先我們引入相應的jar包
使用註解的好處不言而喻,我們就不用再資料庫中再建表,可以依賴jpa或者hibernate幫我們建表了
3、我們配置一下資料庫中相應的實體物件
ProductType.java
/** * 功能:這是產品類別的 * 檔案:ProductType.java * 時間:2015年5月12日10:16:21 * cutter_point */package com.cutter_point.bean.product; import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.SequenceGenerator; @Entity@SequenceGenerator(name="seq_1",sequenceName="seq_1",allocationSize=1,initialValue=1)public class ProductType{ /** 類型id **/ privateInteger typeid; privateString name; //類別名 privateString note; //備忘,用於百度搜尋 privateboolean visible = true; //是否可見 publicProductType() { } @Column(length=36,nullable=false) publicString getName() { returnname; } publicvoid setName(String name) { this.name= name; } @Column(length=200) publicString getNote() { returnnote; } publicvoid setNote(String note) { this.note= note; } @Column(nullable=false) publicboolean isVisible() { returnvisible; } publicvoid setVisible(boolean visible) { this.visible= visible; } @Id @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq_1") //自增長 publicInteger getTypeid() { returntypeid; } publicvoid setTypeid(Integer typeid) { this.typeid= typeid; }}
這裡的xml檔案我們也不必去配置了
4、我們配置一下spring的設定檔beans.xml
<?xml version="1.0"encoding="UTF-8"?><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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.1.xsd"> <!-- 掃描帶有spring特殊機制的類,這是把這些包下面所有的類都添加到spring中進行管理 --> <context:component-scan base-package="com.cutter_point" /> <!-- 屬性遍曆器 --> <!-- <context:property-placeholderlocation="classpath:jdbc.properties" /> --> <!-- 串連資料庫屬性配置,destroy-method="close"就是說在這個bean被摧毀的情況下可以調用這個bean預設的close方法--> <bean id="myDataSource" class="org.apache.commons.dbcp2.BasicDataSource"destroy-method="close"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> <property name="url"value="jdbc:oracle:thin:@localhost:1522:orcl"/> <property name="username"value="xf1205020116"/> <property name="password"value="xf1205020116"/> <!-- 串連池啟動時的初始值 --> <property name="initialSize" value="1"/> <!-- 串連池的最大值 dbcp2裡面似乎沒有--> <!-- <property name="maxActive"value="500"/> --> <!-- 最大空閑值.當經過一個高峰時間後,串連池可以慢慢將已經用不到的串連慢慢釋放一部分,一直減少到maxIdle為止 --> <property name="maxIdle" value="2"/> <!-- 最小空閑值.當閒置串連數少於閥值時,串連池就會預申請去一些串連,以免洪峰來時來不及申請 --> <property name="minIdle" value="1"/> </bean> <!-- hibernate二級緩衝的配置 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!-- configuration elided for brevity --> <property name="dataSource" ref="myDataSource" /> <!-- <propertyname="mappingResources"> <list> 對應檔 <value>com/cutter_point/bean/product/ProductType.hbm.xml</value> </list> </property>--> <property name="hibernateProperties"> <!-- 用來配置hibernate的屬性配置 --> <value> hibernate.dialect=org.hibernate.dialect.OracleDialect hibernate.hbm2ddl.auto=update <!--其他取值 create、create-drop、update、validate none--> hibernate.show_sql=true hibernate.format_sql=true <!-- 開啟二級緩衝功能 --> hibernate.cache.use_second_level_cache= true hibernate.cache.use_query_cache= false hibernate.cache.region.factory_class= org.hibernate.cache.ehcache.EhCacheRegionFactory <!-- hibernate3的二級緩衝配置 --> <!-- <propertyname="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>--> </value> </property> <property name="packagesToScan" value="com.cutter_point.bean" /> </bean> <!-- 交易管理員,吧上面配置的bean注入到這個裡面 --> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 我們採用註解的方式來使用這個事務,首先我們開啟事務 --> <tx:annotation-driven transaction-manager="txManager" /> </beans>
注意我們的spring設定檔裡面也不必再寫對應的xml檔案在哪了
5、接下來我們用spring的IOC/DI(依賴注入)功能
這裡我們可能還會接觸到另外一個名詞叫:控制反轉 好的現在我們來講講這兩個名詞是什麼,幹什麼用的!
依賴注入:1、誰依賴於誰
當然是某個對象依賴於IoC/DI的容器,也就是spring容器了
2、為什麼需要依賴
對象需要IoC/DI的容器來提供對象需要的外部資源
3、誰注入於誰:
很明顯是IoC/DI的容器 注入 某個對象
4、到底注入什麼:
就是注入某個對象所需要的外部資源
控制反轉:
1、誰控制誰:
當然是IoC/DI的容器來控制對象了
2、控制什麼:
主要是控制對象執行個體的建立
3、為何叫反轉
反轉是相對於正向而言的,那麼什麼算是正向的呢?考慮一下常規情況下的應用程式,如果要在A裡面使用C,你會怎麼做呢?當然是直接去建立C的對象,也就是說,是在A類中主動去擷取所需要的外部資源C,這種情況被稱為正向的。那麼什麼是反向呢?就是A類不再主動去擷取C,而是被動等待,等待IoC/DI的容器擷取一個C的執行個體,然後反向的注入到A類中
用圖例來說明一下,先看沒有IoC/DI的時候,常規的A類使用C類的,7所示:
圖7 常規A使用C
當有了IoC/DI的容器後,A類不再主動去建立C了,8所示:
圖8 A類不再主動建立C
而是被動等待,等待IoC/DI的容器擷取一個C的執行個體,然後反向的注入到A類中,9所示:
圖9 有IoC/DI容器後程式結構
小結:
所以說,這兩個名詞從本質上沒有什麼差別
依賴注入是從應用程式的角度在描述,可以把依賴注入描述完整點:應用程式依賴容器建立並注入它所需要的外部資源;而控制反轉是從容器的角度在描述,描述完整點:容器控制應用程式,由容器反向的嚮應用程式注入應用程式所需要的外部資源。
內容來源:http://baitai.iteye.com/blog/792980
6、使用依賴注入
首先實現一個業務介面
ProductService.java
package com.cutter_point.service.product; import com.cutter_point.bean.product.ProductType; publicinterfaceProductService{ publicabstractvoid save(ProductType type); }
實現介面ProductServiceBean.java
/** * 功能:這是產品類別的服務類 * 檔案:ProductServiceBean.java * 時間:2015年5月13日15:36:06 * cutter_point */package com.cutter_point.service.product.impl; import javax.annotation.Resource; import org.hibernate.SessionFactory;importorg.springframework.stereotype.Service;importorg.springframework.transaction.annotation.Transactional; importcom.cutter_point.bean.product.ProductType;importcom.cutter_point.service.product.ProductService; @Service //相當於在spring裡面定義一個bean,這是註解的方式<context:component-scanbase-package="com.cutter_point" />@Transactional //在方法執行的時候開啟事務public class ProductServiceBean implementsProductService{ @Resource //依賴注入sessionFactory SessionFactorysessionFactory; @Override publicvoid save(ProductType type) {// sessionFactory.getCurrentSession().save(type); sessionFactory.getCurrentSession().persist(type); }}
7、接下來我們測試一下hibernate+spring的註解是否配置成功
/** * 功能:這是產品類別的單元測試 * 檔案:ProductTest.java * 時間:2015年5月12日10:27:24 * cutter_point */package junit.test; import javax.sql.DataSource; import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import org.junit.BeforeClass;import org.junit.Test;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext; importcom.cutter_point.bean.product.ProductType;import com.cutter_point.service.product.ProductService; public class ProductTest{ @BeforeClass publicstatic void setUpBeforeClass() throws Exception { } @Test publicvoid test() { ProductTypept = new ProductType(); //new一個對象 pt.setTypeid(78); //設定id號碼 Configurationcfg = new Configuration(); //得到Configuration SessionFactorysf =cfg.configure("/config/hibernate/hibernate.cfg.xml").buildSessionFactory(); //取得session工廠 Sessionsession = sf.openSession(); session.beginTransaction(); session.save(pt); session.getTransaction().commit(); session.close(); sf.close(); } @Test publicvoid testSpring() { //測試spring是否可以運作 ApplicationContextcxt = new ClassPathXmlApplicationContext("config/spring/beans.xml"); DataSourcedatasource = (DataSource)cxt.getBean("myDataSource"); //取出一個對象 System.out.println(datasource); //判斷是不是為空白, } @Test publicvoid testSH() { //測試spring是否可以運作 ApplicationContextcxt = new ClassPathXmlApplicationContext("config/spring/beans.xml"); ProductServiceproductService = (ProductService)cxt.getBean("productServiceBean"); //取出一個對象 ProductTypept = new ProductType(); pt.setName("cutter_point"); pt.setNote("非常好"); productService.save(pt); } }
6、總結
上面就是使用了spring的依賴注入功能來進行實現相應的功能,我們有了這個功能之後,我們之後的struts2的頁面控制器action就可以交給spring託管,這樣在struts2的設定檔裡面就可以實現依賴注入,而後service層也就是許多人所說的DAO層,就叫業務層吧,就都可以交給spring託管,只要我們需要用來spring的依賴注入功能的時候,只要在相應的地方加上一個註解就可以了,就比如
@Resource //依賴注入sessionFactory
SessionFactorysessionFactory;
這個就對sessionFactory進行了依賴注入,當然這個在spring中是有配置的,然後我們的service註解
@Service //相當於在spring裡面定義一個bean,這是註解的方式<context:component-scanbase-package="com.cutter_point" />
這個是沒有配置的,這個用的是註解,但是已經交給了spring託管了,所以在test測試類別中我們可以直接使用,就像這樣
ProductService productService =(ProductService)cxt.getBean("productServiceBean"); //取出一個對象
因為加了註解spring就會協助我們管理這個類。
【j2ee spring】28、巴巴運動網-整合hibernate4+spring4(3)使用註解