首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

#对spring的了解

2012-09-03 
#对spring的理解对spring的理解,spring的核心概念(原理+三个重要应用)-spring的优势所在public interface

#对spring的理解

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

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 Injectionpublic 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" /><bean id="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//NetWorkSystem.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 {@Testpublic 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:

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 Controlpublic class UserServiceTest {@Testpublic 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" 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() {                      //getUserDAOreturn userDAO;}public void setUserDAO(UserDAO userDAO) { //setUserDAOthis.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//NetWorkSystem.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;}   @Resourcepublic 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" >  </bean>  </beans>
?
UserServiceTest.java:
import com.bjsxt.model.User;//Dependency Injection//Inverse of Controlpublic class UserServiceTest {@Testpublic void testAdd() throws Exception {ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");UserService service = (UserService)ctx.getBean("userService");service.add(new User());ctx.destroy();}}
?





?

AOP:

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;}}
?? 产生代理对象:
@Testpublic 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:?
?? #对spring的了解
??

@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@Componentpublic 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的整合--示例程序



配置文件:
??? 将dataSource的Bean 和sessionFactory(Hibernate3.AnnotationSessionFactoryBean) 配置到 bean.xml中
???
<bean id="dataSource" destroy-method="close"/><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></bean><bean id="sessionFactory"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;@Entitypublic class User {private int id;private String name;@Id@GeneratedValuepublic 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;}@Resourcepublic 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 Controlpublic 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: 声明式事务管理
#对spring的了解
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"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>--><beandestroy-method="close"/><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></bean><bean id="sessionFactory"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"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;}@Resourcepublic 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;}@Resourcepublic 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;}@Resourcepublic void setLogDAO(LogDAO logDAO) {this.logDAO = logDAO;}public void destroy() {System.out.println("destroy");}}
?

-------------------------------------------------------------
示例3:HibernateTemplate:
?????
????? Spring对Hibernate的一种简单封装,制作一个模板。
??????封装的部分:
????? #对spring的了解
???
??
? 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"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>--><beandestroy-method="close"/><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></bean><bean id="sessionFactory"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"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" 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;}@Resourcepublic void setHibernateTemplate(HibernateTemplate hibernateTemplate) {this.hibernateTemplate = hibernateTemplate;}public void save(User user) {hibernateTemplate.save(user);//throw new RuntimeException("exeption!");}}


模板方式的模拟实现:






示例5:HibernateDaoSupport:
??参考hibernate--2部分的代码










?

热点排行