标签:spring iocdi 依赖注入 控制反转 ssh注解
使用注解的好处不言而喻,我们就不用再数据库中再建表,可以依赖jpa或者hibernate帮我们建表了
/**
* 功能:这是产品类别的
* 文件: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文件我们也不必去配置了
<?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文件在哪了
这里我们可能还会接触到另外一个名词叫:控制反转 好的现在我们来讲讲这两个名词是什么,干什么用的!
当然是某个对象依赖于IoC/DI的容器,也就是spring容器了
对象需要IoC/DI的容器来提供对象需要的外部资源
很明显是IoC/DI的容器 注入 某个对象
就是注入某个对象所需要的外部资源
当然是IoC/DI的容器来控制对象了
主要是控制对象实例的创建
反转是相对于正向而言的,那么什么算是正向的呢?考虑一下常规情况下的应用程序,如果要在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
首先实现一个业务接口
package com.cutter_point.service.product;
import com.cutter_point.bean.product.ProductType;
publicinterfaceProductService
{
publicabstractvoid save(ProductType type);
}
/**
* 功能:这是产品类别的服务类
* 文件: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);
}
}
/**
* 功能:这是产品类别的单元测试
* 文件: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);
}
}
上面就是使用了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)使用注解
标签:spring iocdi 依赖注入 控制反转 ssh注解
原文地址:http://blog.csdn.net/cutter_point/article/details/46407863