#对spring的理解
对spring的理解,spring的核心概念(原理+三个重要应用)->spring的优势所在
public interface BeanFactory {public Object getBean(String id);}?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);}}?<beans><bean id="u" /><bean id="userService" ><property name="userDAO" bean="u"/></bean></beans>?
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;}}?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!");}}?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;}}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);}}?<?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>?
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;}}?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!");}}?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");}}?<?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>?
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());}?
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的整合--示例程序
<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>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;}}package com.bjsxt.dao;import com.bjsxt.model.User;public interface UserDAO {public void save(User user);}?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!");}}?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");}}?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();}}?
<?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>??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!");}}?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!");}}?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");}}?
<?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>?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!");}}?