`

#对spring的理解

阅读更多

对spring的理解,spring的核心概念(原理+三个重要应用)->spring的优势所在

Spring 的原理(反射机制+工厂设计模式)
使用Spring框架,可以通过spring容器来管理对象的创建和使用,可以灵活地将对象注入到其他对象中去

Spring模拟实现代码:
1.Spring核心:
    BeanFactory.java:
public interface BeanFactory {
	public Object getBean(String id);
}
 
   ClassPathXmlApplicationContext.java
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class ClassPathXmlApplicationContext implements BeanFactory {
	
	private Map<String , Object> beans = new HashMap<String, Object>();
	
	
	//IOC Inverse of Control DI Dependency Injection
	public ClassPathXmlApplicationContext() throws Exception {
		SAXBuilder sb=new SAXBuilder();
		 
	  Document doc=sb.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml")); //构造文档对象
	  Element root=doc.getRootElement(); //获取根元素HD
	  List list=root.getChildren("bean");//取名字为disk的所有元素
	  
	  for(int i=0;i<list.size();i++){
	  	Element element=(Element)list.get(i);
	  	String id=element.getAttributeValue("id");
	  	String clazz=element.getAttributeValue("class");
	  	Object o = Class.forName(clazz).newInstance();
	  	System.out.println(id);
	  	System.out.println(clazz);
	  	beans.put(id, o);
	       
	  	for(Element propertyElement : (List<Element>)element.getChildren("property")) {
	  		String name = propertyElement.getAttributeValue("name"); //userDAO
	  		String bean = propertyElement.getAttributeValue("bean"); //u
	  		Object beanObject = beans.get(bean);//UserDAOImpl instance
	    	   
	  		String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
	  		System.out.println("method name = " + methodName);
	    	   
	  		Method m = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]);
	  		m.invoke(o, beanObject);
	    }	       
	  }  
	}

	public Object getBean(String id) {
		return beans.get(id);
	}

}
 
bean.xml:
<beans>
	<bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl" />
	<bean id="userService" class="com.bjsxt.service.UserService" >
		<property name="userDAO" bean="u"/>
	</bean>
	
</beans>
 


2. Model层:
    User.java
public class User {
	private String username;
	private String password;
	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;
	}
}
 




3. DAO层:

UserDAOImpl.java
import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.User;

public class UserDAOImpl implements UserDAO {

	public void save(User user) {
		//Hibernate
		//JDBC
		//XML
		//NetWork
		System.out.println("user saved!");
	}

}
 



5. service层:
import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.User;

public class UserService {
	private UserDAO userDAO;  
	public void add(User user) {
		userDAO.save(user);
	}
	public UserDAO getUserDAO() {
		return userDAO;
	}
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
}

6. 应用层

public class UserServiceTest {

	@Test
	public void testAdd() throws Exception {
		BeanFactory applicationContext = new ClassPathXmlApplicationContext();
		UserService service = (UserService)applicationContext.getBean("userService");
				
		User u = new User();
		u.setUsername("zhangsan");
		u.setPassword("zhangsan");
		service.add(u);
	}

}
 













 

 

DI:

1 DI的概念
2 DI举例说明
    2.1 简单实例
    2.2 Spring整合Struts
    2.3 Spring整合Hibernate

 
DI(依赖注入):对象的实例由spring容器来创建、并注入到使用该对象实例的程序中 或者 由程序员去容器中取出对象的实例;而不需要程序员去创建该对象的实例。

实例1:通过在bean.xml中配置 对象的信息,由spring容器创建对象实例,程序员使用对象时从容器中去取
package com.bjsxt.service;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bjsxt.model.User;

//Dependency Injection
//Inverse of Control
public class UserServiceTest {

	@Test
	public void testAdd() throws Exception {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		UserService service = (UserService)ctx.getBean("userService");
		
		User u = new User();
		u.setUsername("zhangsan");
		u.setPassword("zhangsan");
		
		service.add(u);
	}

}
 


实例2:通过在bean.xml文件中配置对象A依赖对象B,在对象A中获得一个对象B的实例(注意需要在A中加入B的引用以及B的get和set方法)

bean.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

  <bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl">
  </bean>
	
  <bean id="userService" class="com.bjsxt.service.UserService">
  	<property name="userDAO" ref="u" />
  		
  </bean>
  

</beans>
 
UserService.java:
package com.bjsxt.service;
import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.User;

public class UserService {
	private UserDAO userDAO;                              //加入userDAO的引用

	public void add(User user) {
		userDAO.save(user);
	}

	public UserDAO getUserDAO() {                      //getUserDAO
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) { //setUserDAO
		this.userDAO = userDAO;
	}
}
 

实例3:属性注入,采用注解和get、set方法:
 
UserDAOImpl.java:

package com.bjsxt.dao.impl;
import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.User;

public class UserDAOImpl implements UserDAO {
	public void save(User user) {
		//Hibernate
		//JDBC
		//XML
		//NetWork
		System.out.println("user saved!");
	}
}
 

UserService.java:
package com.bjsxt.service;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.User;

public class UserService {
	
	private UserDAO userDAO;  
	
	public void init() {
		System.out.println("init");
	}
	
	public void add(User user) {
		userDAO.save(user);
	   }

	public UserDAO getUserDAO() {
		return userDAO;
	}
	
	   @Resource
	public void setUserDAO( UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	

	
	public void destroy() {
		System.out.println("destroy");
	}
}
 
bean.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"
       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 />

  <bean id="userDAO" class="com.bjsxt.dao.impl.UserDAOImpl">
  </bean>
 
  <bean id="userService" class="com.bjsxt.service.UserService" >
  </bean>
  

</beans>
 
UserServiceTest.java:
import com.bjsxt.model.User;

//Dependency Injection
//Inverse of Control
public class UserServiceTest {

	@Test
	public void testAdd() throws Exception {
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		
		UserService service = (UserService)ctx.getBean("userService");
		service.add(new User());
		
		ctx.destroy();
		
	}

}
 





 

AOP:

1  AOP的概念
2  AOP的原理(AOP与动态代理)
    2.1  模拟代码
    2.2  Spring中的AOP的相关概念
    2.3  Spring中的AOP的应用举例
    
1  AOP的概念:
    AOP: 面向切面编程 Aspect-Oriented-Programming
    例如:在一个方法执行之前或者之后加一些代码 (一些业务逻辑),即动态织入一些额外的代码。
    如何实现呢? 1. 继承原有类   2. 采用组合的方式,创建原有类的一个代理   3. 使用拦截器(面向切面编程)

     好处可以动态的添加和删除在切面上的逻辑,而不影响到原来的代码。
   
    AOP应用实例 Servlet Filter, Struts2 的Interceptor


2  AOP的原理(AOP与动态代理)
2.1 模拟AOP的实现代码(采用动态代理的方法)

为什么要用动态代理?
      拦截器可以动态地代理所有需要代理的以及方法,这些类需要在bean.xml文件中配置该拦截器。
      
实现:用JDK提供的 Proxy类和 InvocationHandler类来实现
拦截器: LogInterceptor.java
package com.bjsxt.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class LogInterceptor implements InvocationHandler {
	private Object target;
	
	public Object getTarget() {
		return target;
	}

	public void setTarget(Object target) {
		this.target = target;
	}

	public void beforeMethod(Method m) {
		
		System.out.println(m.getName() + " start");
	}

	public Object invoke(Object proxy, Method m, Object[] args)
			throws Throwable {
		beforeMethod(m);              // 加入新的逻辑
		m.invoke(target, args);      // 调用被代理对象的方法
		return null;
	}
}

   产生代理对象:
	@Test
	public void testProxy() {
		UserDAO userDAO = new UserDAOImpl();             //被代理对象
		LogInterceptor li = new LogInterceptor();        //拦截器
		li.setTarget(userDAO);
		
		// 产生代理对象
		UserDAO userDAOProxy = (UserDAO)Proxy.newProxyInstance(userDAO.getClass().getClassLoader(), userDAO.getClass().getInterfaces(), li);
		System.out.println(userDAOProxy.getClass());
		userDAOProxy.delete();
		userDAOProxy.save(new User());
		
	}
	
 

2.2  Spring中的AOP的相关概念

概念:
1. joinpoint: 代码执行过程中被拦截的地方 (例如:被拦截的方法之前)

2. pointcut:  joinpoint(切入点)的一个集合。
     例如:
      @Pointcut("execution(public * com.bjsxt.service..*.add(..))")
      public void myMethod(){}; (pointcut的名字)

3. aspect: 切面上的逻辑。例如:拦截器Interceptor
    
5. Target: 被代理的对象
 
6. weave: 织入
 



常见的Annotation: 
  
  

@before: 方法执行前
@AfterThrowing: catch到异常时执行
@AfterReturning:  在方法返回之前
@After: finally时执行的代码
@Around: 在执行之前和之后都可以执行。 回忆servlet filter
@Pointcut:为切面类的方法配置需要被拦截的点
   

 2.3  Spring中的AOP的应用实例:
    
package com.bjsxt.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogInterceptor {
	@Pointcut("execution(public * com.bjsxt.service..*.add(..))")
	public void myMethod(){};
	
	@Before("myMethod()")
	public void before() {
		System.out.println("method before");
	}
	
	@Around("myMethod()")
	public void aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
		System.out.println("method around start");
		pjp.proceed();
		System.out.println("method around end");
	}
	
}
 





 

 

 

 Spring+Hibernate的整合--示例程序

1.示例1


配置文件:
    将dataSource的Bean 和sessionFactory(Hibernate3.AnnotationSessionFactoryBean) 配置到 bean.xml中
   
	<bean id="dataSource" destroy-method="close"
		class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName"
			value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="annotatedClasses">
			<list>
				<value>com.bjsxt.model.User</value><!--注解的实体类-->
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQLDialect
				</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>

 User.java
package com.bjsxt.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;


@Entity
public class User {
	private int id;
	private String name;
	
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}

  UserDAO.java:
package com.bjsxt.dao;
import com.bjsxt.model.User;


public interface UserDAO {
	public void save(User user);
}
 
  UserDAOImpl.java

package com.bjsxt.dao.impl;
import java.sql.SQLException;
import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.User;

@Component("u") 
public class UserDAOImpl implements UserDAO {

	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public void save(User user) {
	               System.out.println("session factory class:" + sessionFactory.getClass());
	               Session s = sessionFactory.openSession();
	               s.beginTransaction();
	               s.save(user);
	               s.getTransaction().commit();
	               System.out.println("user saved!");
	               //throw new RuntimeException("exeption!");
	}

}
 

 UserService.java
package com.bjsxt.service;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.User;


@Component("userService")
public class UserService {
	
	private UserDAO userDAO;  
	
	public void init() {
		System.out.println("init");
	}
	
	public void add(User user) {
		userDAO.save(user);
	}
	
	public UserDAO getUserDAO() {
		return userDAO;
	}
	
	@Resource(name="u")
	public void setUserDAO( UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	

	
	public void destroy() {
		System.out.println("destroy");
	}
}
 
UserServiceTest .java
package com.bjsxt.service;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bjsxt.model.User;

//Dependency Injection
//Inverse of Control
public class UserServiceTest {

	@Test 
	public void testAdd() throws Exception {
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		
		UserService service = (UserService)ctx.getBean("userService");
		System.out.println(service.getClass());
		service.add(new User());
		
		ctx.destroy();
		
	}

}
 

---------------------------------------------------------------------------------------------------------------
示例2: 声明式事务管理

1.  日志信息保存和用户信息保存应在一个事务中进行处理,因此,事务处理应该放在service层来处理
2.  需要使用@Transactional标签
3.  在出现RuntimeException时事务会回滚,Hibernate中的异常都是RuntimeException



<?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/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
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<context:annotation-config />
	<context:component-scan base-package="com.bjsxt" />

	<!-- 
		<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		
		
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/spring" />
		<property name="username" value="root" />
		<property name="password" value="bjsxt" />
		</bean>
	-->

	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<value>classpath:jdbc.properties</value>
		</property>
	</bean>

	<bean id="dataSource" destroy-method="close"
		class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName"
			value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="annotatedClasses">
			<list>
				<value>com.bjsxt.model.User</value>
				<value>com.bjsxt.model.Log</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQLDialect
				</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>

	<bean id="txManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	
	<tx:annotation-driven transaction-manager="txManager"/>

</beans>
  


  LogDAOImpl:
import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import com.bjsxt.dao.LogDAO;
import com.bjsxt.model.Log;

@Component("logDAO") 
public class LogDAOImpl implements LogDAO {

	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public void save(Log log) {
		
		Session s = sessionFactory.getCurrentSession();
		s.save(log);
		//throw new RuntimeException("error!");
	}

}
 
UserDAOImpl:
import java.sql.SQLException;
import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.User;

@Component("u") 
public class UserDAOImpl implements UserDAO {

	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public void save(User user) {
		
			Session s = sessionFactory.getCurrentSession();
			
			s.save(user);
			
		//throw new RuntimeException("exeption!");
	}

}
 

UserService.java
package com.bjsxt.service;
import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.bjsxt.dao.LogDAO;
import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.Log;
import com.bjsxt.model.User;


@Component("userService")
public class UserService {
	
	private UserDAO userDAO;
	private LogDAO logDAO;
	
	public void init() {
		System.out.println("init");
	}
	
	public User getUser(int id) {
		return null;
	}
	
	@Transactional(readOnly=true)
	public void add(User user) {
			userDAO.save(user);
			Log log = new Log();
			log.setMsg("a user saved!");
			logDAO.save(log);
		
	}
	public UserDAO getUserDAO() {
		return userDAO;
	}
	
	@Resource(name="u")
	public void setUserDAO( UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	

	
	public LogDAO getLogDAO() {
		return logDAO;
	}
	
	@Resource
	public void setLogDAO(LogDAO logDAO) {
		this.logDAO = logDAO;
	}

	public void destroy() {
		System.out.println("destroy");
	}
}
 

-------------------------------------------------------------------------------------------------
示例3:HibernateTemplate:
     
      Spring对Hibernate的一种简单封装,制作一个模板。
      封装的部分:
     
   
  
  bean.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/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
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<context:annotation-config />
	<context:component-scan base-package="com.bjsxt" />

	<!-- 
		<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		
		
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/spring" />
		<property name="username" value="root" />
		<property name="password" value="bjsxt" />
		</bean>
	-->

	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<value>classpath:jdbc.properties</value>
		</property>
	</bean>

	<bean id="dataSource" destroy-method="close"
		class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName"
			value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 
		<property name="annotatedClasses">
			<list>
				<value>com.bjsxt.model.User</value>
				<value>com.bjsxt.model.Log</value>
			</list>
		</property>
		 -->
		 <property name="packagesToScan">
			<list>
				<value>com.bjsxt.model</value>
				
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQLDialect
				</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>

	<bean id="txManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<aop:config>
		<aop:pointcut id="bussinessService"
			expression="execution(public * com.bjsxt.service..*.*(..))" />
		<aop:advisor pointcut-ref="bussinessService"
			advice-ref="txAdvice" />
	</aop:config>

	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="getUser" read-only="true" />
			<tx:method name="add*" propagation="REQUIRED"/>
		</tx:attributes>
	</tx:advice>

	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

</beans>
 
  UserDAOImpl.java
  
package com.bjsxt.dao.impl;

import javax.annotation.Resource;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.User;

@Component("u") 
public class UserDAOImpl implements UserDAO {

	private HibernateTemplate hibernateTemplate;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public void save(User user) {
			hibernateTemplate.save(user);
			
		//throw new RuntimeException("exeption!");
	}

}


模板方式的模拟实现:






示例5:HibernateDaoSupport:
  参考hibernate--2部分的代码
在context中定义DataSource,创建SessionFactoy,设置参数;DAO类继承HibernateDaoSupport,实现具体接口,从中获得

HibernateTemplate进行具体操作。在使用中如果遇到OpenSessionInView的问题,可以添加OpenSessionInViewFilter或

OpenSessionInViewInterceptor。
 









 

spring中的Bean的生命周期管理: 
1.Bean的作用域可以通过Bean标签的scope属性进行设置,Bean的作用域包括:

默认情况下scope="singleton",那么该Bean是单例,任何人获取该Bean实例的都为同一个实例;
scope="prototype",任何一个实例都是新的实例;
scope="request",在WEB应用程序中,每一个实例的作用域都为request范围;
scope="session",在WEB应用程序中,每一个实例的作用域都为session范围;
注意:在默认情况下,Bean实例在被Spring容器初始化的时候,就会被实例化,默认调用无参数的构造方法。在其它情况下,Bean将会

在获取实例的时候才会被实例化。

 

2.Bean可以通过指定属性init-method指定初始化后执行的方法,以及通过指定属性destroy-method销毁时执行的方法。

语法:<bean ....   destroy-method="销毁时调用的方法名" init-method="初始化后执行的方法名"/>










 

  • 大小: 12.9 KB
  • 大小: 3.1 KB
  • 大小: 10.5 KB
  • 大小: 54.7 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics