spring

  • 格式:doc
  • 大小:180.00 KB
  • 文档页数:19

wanght@一、IoC - Inverse Of Control; DI - Depandency Injection基本注入<bean id="zhangsan"class="tarena.spring.ioc.Person"> <!-- Person.setName("张三") --><property name="name"value="张三"/><property name="age"><!-- Person.setAge(18) --><value>18</value></property><property name="tels"><list><!-- xxx[], List, Set --><value>4948631</value><value>2645234</value><value>5674567</value></list></property></bean><bean id="car"class="tarena.spring.ioc.Car"><!--Car.setDriver(...)ref 引用spring创建的id=zhangsan的对象--><property name="driver"ref="zhangsan"/><!--Car.setProps()Properties类型字符串键值对--><property name="props"><props><prop key="color">Red</prop><prop key="weight">1.5t</prop><prop key="brand">BMW</prop></props></property><!--Map类型--><property name="drivers"><map><entry key="正驾"><ref bean="zhangsan"/></entry><entry key="副驾"><!-- 注入时直接创建对象 --><bean class="tarena.spring.ioc.Person"><property name="name"value="李四"/></bean></entry></map></property></bean><!-- 构造方法注入 --><bean id="wangwu"class="tarena.spring.ioc.Person"> <constructor-arg index="0"><value>王五</value></constructor-arg><constructor-arg index="1"><value>22</value></constructor-arg><constructor-arg index="2"><list><value>6523452345</value><value>6543563456</value></list></constructor-arg></bean>IoC - 自动注入<bean id="cpu"class="tarena.spring.ioc.auto.Cpu"/><bean id="hardDisk"class="tarena.spring.ioc.auto.HardDisk"/> <bean id="memory"class="tarena.spring.ioc.auto.Memory"/><!-- 快速原型可以使用自动装配 byName, byType, autodetect --> <bean id="computer"class="puter"autowire="byName"/>IoC - abstract, 继承<!-- abstract 不会创建对象 --><bean id="abstractCar"class="tarena.spring.ioc.Car"abstract="true"><property name="drivers"><map><entry key="副驾"><bean class="tarena.spring.ioc.Person"><property name="name"value="张三"/></bean></entry></map></property><property name="props"><props><prop key="color">Red</prop></props></property></bean><!-- 继承相同的配置,修改或添加不同的配置 --><bean id="car"parent="abstractCar"><property name="driver"><bean class="tarena.spring.ioc.Person"><property name="name"value="李四"/></bean></property></bean>IoC - 静态工厂方法创建对象<!-- CarFactory.getCar() 静态方法获得Car对象 --><bean id="car"class="tarena.spring.ioc.factory.CarFactory"factory-method="getCar"><!-- Car 的属性 --><property name="props"><props><prop key="color">Blue</prop></props></property></bean>IoC - 非静态工厂方法创建对象<!-- 创建工厂对象实例 --><bean id="bmwFactory"class="tarena.spring.ioc.factory.CarFactory"> <property name="brand"value="BMW"/></bean><!-- bmwFactory.createCar 创建 Car 实例 --><bean id="bmwCar"factory-bean="bmwFactory"factory-method="createCar" />IoC - scope<!--scope="singleton" getBean返回同一个实例,默认"prototype" getBean返回新实例"request" web应用中request范围内缓存实例"session" web应用中session范围内缓存实例--><bean id="bmwCar"factory-bean="bmwFactory"factory-method="createCar"scope="prototype"/>IoC - ApplicationContextAware// spring创建Person对象时,判断是否是ApplicationContextAware的子类型// 如果是,调用setApplicationContext(),自动装配spring容器public class Person implements ApplicationContextAware { // 其他属性// spring 容器对象private ApplicationContext ac;// 接口的抽象方法public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {this.ac = applicationContext;}IoC - Listener// 实现spring 事件接口public class AgeEvent extends ApplicationEvent{public AgeEvent(Object o) {super(o);}}---------------------------------------------------------------// 事件spring 监听器接口public class AgeListener implements ApplicationListener { public void onApplicationEvent(ApplicationEvent event) { if(event instanceof AgeEvent) {System.out.println("年龄不正确");}}}---------------------------------------------------------------// 业务方法中发布异常,ac 是 spring容器对象public void setAge(int age) {if(age<0 || age>100) {AgeEvent event = new AgeEvent(this);ac.publishEvent(event);return;}this.age = age;}---------------------------------------------------------------<!-- 在 spring 容器中创建监听器对象 --><bean class="tarena.spring.ioc.listener.AgeListener"/>IoC - PostProcessor, PropertyPlaceholderConfigurer<!-- spring 加载配置文件后,使用后处理器修改配置信息 --><bean id="dbutil"class="tarena.spring.ioc.postprocess.DBUtil"> <property name="url"value="${url}"/><property name="driver"value="${driver}"/><property name="username"value="${username}"/><property name="password"value="${password}"/></bean><!--PropertyPlaceholderConfigurer是一个后处理器,它加载db.properties文件中的数据,把前面的${}替换为具体值--><beanclass="org.springframework.beans.factory.config.PropertyPlaceholderConfigure r"><property name="location"value="db.properties"/></bean>IoC - Property editor// 继承PropertyEditorSupportimport java.beans.PropertyEditorSupport;public class AddressEditor extends PropertyEditorSupport {@Overridepublic void setAsText(String text)throws IllegalArgumentException {String[] arr = text.split("-");Address address = new Address();address.setCity(arr[0]);address.setStreet(arr[1]);setValue(address);}}<!-- 在 spring 配置中,Address类型的对象直接赋字符串值 --><bean id="person"class="tarena.spring.ioc.Person"><property name="name"value="张三"/><property name="address"value="北京-北三环联想桥中鼎大厦"/></bean><!-- 创建属性编辑器 --><beanclass="org.springframework.beans.factory.config.CustomEditorConfigurer"><property name="customEditors"><map><entry><key><value>tarena.spring.ioc.Address</value></key><bean class="tarena.spring.ioc.propeditor.AddressEditor"/></entry></map></property></bean>IoC - 子环境// 加载根环境ApplicationContext ac =new ClassPathXmlApplicationContext("tarena/spring/ioc/subcontext/applicationContext.xml");// 加载子环境,将根环境对象 ac 传入ApplicationContext acSub =New ClassPathXmlApplicationContext(new String[]{"tarena/spring/ioc/subcontext/applicationContext-sub.xml"}, ac);二、AOPSpring AOP<!-- 创建业务对象 --><bean id="shopTarget"class="tarena.spring.aop.Shop"/><!-- 创建前拦截器(切片) --><bean id="buyBookBefor"class="tarena.spring.aop.BuyBookBefor"/><!-- 创建后拦截器(切片) --><bean id="buyBookAfter"class="tarena.spring.aop.BuyBookAfter"/><!-- 选择切入点(方法)的拦截器,封装其他拦截器 --><bean id="buyBookAfterAdvisor"class="MatchMethodPointcutAdvisor"> <property name="advice"ref="buyBookAfter"/><property name="mappedNames"><list><value>buyBook</value><value>returnBook</value></list></property></bean><!-- 创建代理对象,指定实现的业务接口、转发目标对象、拦截器 --><bean id="shop"class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="interfaces"><list><value>tarena.spring.aop.IShop</value></list></property><property name="target"ref="shopTarget"/><property name="interceptorNames"><list><value>buyBookAfterAdvisor</value><value>buyBookBefor</value></list></property></bean>Spring AOP - 五种拦截器// 前拦截public class BuyBookBefor implements MethodBeforeAdvice { public void before(Method m, Object[] args, Object o)throws Throwable {System.out.println("欢迎光临");}}// 后拦截public class BuyBookAfter implements AfterReturningAdvice{ public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { System.out.println("下次再来");}}// 环绕拦截public class BuyBookArround implements MethodInterceptor { public Object invoke(MethodInvocation mi) throws Throwable { System.out.println("您来了");Object o = mi.proceed();// 转发调用System.out.println("您慢走");return o;}}// 异常拦截,方法不是接口的抽象方法,声明格式参考接口的文档public class BuyBookThrows implements ThrowsAdvice { public void afterThrowing(Exception e) {System.out.println("对不起,购书失败");}}// introduction拦截,在代理中引入其他业务接口和业务对象// 创建代理时,指定代理实现IShopStatus接口public class ShopStatusextends DelegatingIntroductionInterceptorimplements IShopStatus {public boolean closed = false;public void close() {closed = true;}public void open() {closed = false;}@Overridepublic Object invoke(MethodInvocation mi) throws Throwable { if(implementsInterface(mi.getMethod().getDeclaringClass())) {return mi.getMethod().invoke(this, mi.getArguments());}if(! closed) {return mi.proceed();} else {System.out.println("商店关闭");return null;}}}Aspectj AOPAspectj 拦截器execution指定切入点@Aspectpublic class ShopAspect {@Before("execution(* buy*(..))")public void buyBookBefore() {System.out.println("欢迎光临");}@AfterReturning(value="execution(* buy*(..))",returning="book")public void buyBookAfter(Book book) {System.out.println(book);System.out.println("下次再来");}@Around("execution(* buy*(..))")public void buyBookAround(ProceedingJoinPoint pjp)throws Throwable {System.out.println("您来了");// 转发Object o=pjp.proceed();System.out.println("您慢走");}@AfterThrowing(value="execution(* buy*(..))",throwing="e")public void afterThrowing(Exception e) {System.out.println("不能买书:"+e.getMessage());}@DeclareParents(value="tarena.spring.aop.Shop",defaultImpl=tarena.spring.aop.aspectj.Restaurant.class) public IRestaurant restaurant;}Spring Aspect 配置<!-- 启用 Aspectj --><aop:aspectj-autoproxy/><!-- 创建业务对象,会被 Aspectj自动代理 --><bean id="shop"class="tarena.spring.aop.Shop"/><!-- 创建拦截器 --><bean id="shopAspect"class="tarena.spring.aop.aspectj.ShopAspect"/>三、JDBC1.JDBC –持久层:datasource<bean id="datasource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="url"><value>jdbc:mysql://localhost:3306/test</value></property><property name="driverClassName"value="com.mysql.jdbc.Driver"/><property name="username"value="root"/><property name="password"value="root"/></bean>2.JDBC – DAO:JdbcDaoSupportpublic class CourseDAOJdbcImpl extends JdbcDaoSupportimplements ICourseDAO { // 从父类JdbcDaoSupport继承了:// setDataSource getDataSource// getJdbcTemplatepublic void delete(Course course) throws Exception {getJdbcTemplate().update("delete from t_course where id=?",new Object[] {course.getId()});}public Course findById(Integer id) throws Exception {List list = getJdbcTemplate().query("select * from t_course where id=?",new Object[]{id},new CourseRowMapper());return (Course)DataAccessUtils.uniqueResult(list);}public static class CourseRowMapper implements RowMapper {public Object mapRow(ResultSet rs, int rowNum)throws SQLException {Course c = new Course();c.setId(rs.getInt("id"));c.setName(rs.getString("name"));return c;}}}<!-- spring中创建dao 对象 --><bean id="courseDAO"class="tarena.spring.jdbc.dao.impl.CourseDAOJdbcImpl"><property name="dataSource"ref="datasource"/></bean>3.JDBC 业务层①JDBC –业务层:Spring AOP切入事务<!-- 创建业务对象 --><bean id="courseServiceTarget"class="tarena.spring.jdbc.service.impl.CourseServiceImpl"> <property name="courseDAO"ref="courseDAO"/></bean><!-- 创建事务管理器 --><bean id="txMgr"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource"ref="datasource"/></bean><!-- 创建代理对象 --><bean id="courseService"class="org.springframework.transaction.interceptor.TransactionProxyFactor yBean"><!-- 实现的业务接口 --><property name="proxyInterfaces"><list><value>tarena.spring.jdbc.service.ICourseService</value></list></property><!-- 转发目标对象 --><property name="target"ref="courseServiceTarget"/><!-- 事务管理器 --><property name="transactionManager"ref="txMgr"/><property name="transactionAttributes"><props><!--<prop key="方法名">事务传播性</prop>--><prop key="update*">PROPAGATION_REQUIRED,-Exception</prop><prop key="find*">PROPAGATION_REQUIRED,readOnly</prop><prop key="*">PROPAGATION_REQUIRED,readOnly</prop> </props></property></bean>REQUIRED无事务,自己启动事务有事务,参与事务REQUIRES_NEW无事务,自己启动事务有事务,自己启动事务,前面的事务会暂时挂起SUPPORT无事务,也无事务有事务,参与事务NOT_SUPPORT无事务,也无事务有事务,也无事务,前面的事务会暂时挂起MANDATORY无事务,抛异常有事务,参与事务NEVER无事务,也无事务有事务,抛异常②JDBC –业务层:Aspectj自动切入事务<!-- 该拦截器封装事务管理器,配置事务传播性 --><tx:advice id="txAdvice"transaction-manager="txMgr"><tx:attributes><tx:method name=" *"propagation="REQUIRED"/><tx:method name="update*"propagation="REQUIRED"rollback-for="Exception"/><tx:method name="find*"propagation="REQUIRED"read-only="true"/></tx:attributes></tx:advice><!--配置切入点:service包中所有方法并在制定切入点事切入 txAdvice 切片--><aop:config><aop:pointcut id="allServiceMethod"expression="execution(* tarena.spring.jdbc.service.*.*(..))"/><aop:advisor advice-ref="txAdvice"p ointcut-ref="allServiceMethod"/></aop:config><!--创建业务对象,程序中使用 courseService得到的是 Aspectj 自动创建的代理对象--><bean id="courseService"class="tarena.spring.jdbc.service.impl.CourseServiceImpl"> <property name="courseDAO"ref="courseDAO"/></bean>③JDBC –业务层:Spring annotation 切入事务业务方法添加 @Transactional 注解@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)public void update(Course c) throws Exception {…………Spring 配置中启用注解<tx:annotation-driven transaction-manager="txMgr"/>四、SSH1.SSH 持久层 - Hibernate<!-- 加载 hibernate 配置文件,创建 sessionFactory --><bean id="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation"value="classpath:hibernate.cfg.xml"></property></bean>2.SSH DAO 层DAO 继承 HibernateDaoSupport,使用 HibernateTemplaate 操作数据public class BanjiDAOHibernateImplextends HibernateDaoSupportimplements IBanjiDAO {public Banji findById(Integer id) throws Exception {return (Banji)getHibernateTemplate().get(Banji.class, id);}}public List<Course> findByName(final String name) throws Exception { /*return getHibernateTemplate().find("from Course c where =?",new Object[]{name});*/return (List)getHibernateTemplate().execute(new HibernateCallback() {public Object doInHibernate(Session session)throws HibernateException, SQLException {return session.createCriteria(Course.class).add(Restrictions.like("name", "%"+name+"%")).list();}});}Spring 配置,创建DAO对象<bean id="banjiDAO"class="spring.tarena.ssh2.dao.impl.BanjiDAOHibernateImpl"> <property name="sessionFactory"ref="sessionFactory"/></bean>3.SSH 业务层同 JDBC 业务层,见 JDBC 业务层这一节4.SSH 表示层 - Struts①Web.xml<!--该监听器负责加载spring配置文件,创建 ApplicationContext 对象,并放入 application--><listener><listener-class>org.springframework.web.context.ContextLoaderListener </listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/classes/applicationContext.xml</param-value></context-param><!--该过滤器在表示层打开 session,并在表示层执行完之后向用户作响应时关闭session--><filter><filter-name>OpenSessionInViewFilter</filter-name><filter-class>org.springframework.orm.hibernate3.support.OpenSessionInVie wFilter</filter-class></filter><filter-mapping><filter-name>OpenSessionInViewFilter</filter-name><url-pattern>*.do</url-pattern></filter-mapping>②Struts-config.xml<!--用户访问sruts时,该请求处理器处理用户请求,委托给 spring,在 spring 容器中找到 action 对象执行--><controller><set-property property="processorClass"value="org.springframework.web.struts.DelegatingRequestProcessor"/></controller><message-resources parameter="ApplicationResources"/><!--Spring 配置文件 struts-actions.xml在这个配置文件中创建 action 对象,作为 spring 的子环境加载--><plug-inclassName="org.springframework.web.struts.ContextLoaderPlugIn"><set-property property="contextConfigLocation"value="/WEB-INF/struts-actions.xml"/></plug-in>③struts-actions.xml<!--创建action对象,用路径作为名字--><bean name="/XueshengList"class="spring.tarena.ssh2.view.XueshengAction"> <property name="xsServ"ref="xueshengService"/></bean>。