Spring使用总结
一、基础JAR包
spring-beans.jar spring-context.jar spring-core.jar spring-expression.jar
二、XML的配置
1、一级结构
- <?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="..." class="...">
- <!-- collaborators and configuration for this bean go here -->
- </bean>
- </beans>
元数据的基本结构
- <import resource="/resources/themeSource.xml"/> <!-- 导入bean -->
- <alias name="studentsManagerService" alias="studentsManagerService2"/> <!-- 别名 -->
- <bean id="exampleBean" class="examples.ExampleBean"/> <!-- 构造器构造 -->
- <bean id="exampleBean" class="examples.ExampleBean2" factory-method="createInstance"/> <!-- 静态工厂方法实例化 -->
- <bean id="serviceLocator" class="com.foo.DefaultServiceLocator"></bean>
- <bean id="exampleBean" factory-bean="serviceLocator" factory-method="createInstance"/> <!-- 实例工厂方法实例化 -->
- <bean id="beanOne" class="ExampleBean" depends-on="manager,accountDao"></bean> <!-- depends-on 初始化/销毁时的依赖 -->
- <bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>
- <beans default-lazy-init="true"></beans> <!-- depends-on 初始化/销毁时的依赖 -->
- <bean id="" class="" autowire="byType"> <!-- 自动装配 常用byName、byType, autowire-candidate="false" bean排除在自动装配之外 -->
- <bean id="ernie" class="com.***." dependency-check="none"> <!-- 默认值,不进行任何检查 --><bean id="ernie" class="com.***." dependency-check="simple"> <!-- 简单类型属性以及集合类型检查 --><bean id="ernie" class="com.***." dependency-check="object"> <!-- 引用类型检查 --><bean id="ernie" class="com.***." dependency-check="all"> <!-- 全部检查 -->
- <!-- 作用域 默认singleton(单实例),prototype每次请求一个实例,request/session/global session -->
<bean id="obj" class="com.***." init-method="init" destroy-method="destroy" scope="prototype"/>
2、参数
- <constructor-arg type="int" value="7500000"/>
- <constructor-arg index="0" value="7500000"/>
- <constructor-arg><bean class="x.y.Baz"/></constructor-arg> <!-- 构造器注入/静态方法参数 不提倡 -->
<property name="beanTwo" ref="yetAnotherBean"/> <!-- Set注入 提倡 -->
- <value>
- jdbc.driver.className=com.mysql.jdbc.Driver
- jdbc.url=jdbc:mysql://localhost:3306/mydb
- </value> <!-- java.util.Properties实例 提倡 -->
- <idref bean="theTargetBean" /> <!-- 同value 校验bean [theTargetBean] 是否存在,不同于ref,ref为引和实例 -->
- <list/>、<set/>、<map/> <props/> <!-- 集合 对应List、Set、Map及Properties的值-->
3、注解
- <?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/>
- </beans>
注解(<context:annotation-config/>)
spring注解命名空间(org.springframework.beans.factory.annotation.*) //常用:Autowired、Qualifier
javax注解命名空间(javax.annotation.*) //常用:Resource、PostConstruct、PreDestroy
spring组件命名空间(org.springframework.stereotype.*) //常用:Component、 Repository、Service、Controller
- @Autowired(required = false)
- private Student student2; //自动注解,有且仅有一个bean(当添加required = false时 没有bean也不会报错 ))
- @Autowired
- @Qualifier("cs2")
- private Student student2; //指定bean cs2,Autowired/Qualifier 可用于字段,Set方法,传值方法
- //@Resource(name="mainCatalog") 与@Autowired类似
- @Autowired
- public void prepare(@Qualifier("mainCatalog") MovieCatalog movieCatalog, CustomerPreferenceDao customerPreferenceDao) {
- this.movieCatalog = movieCatalog;
- this.customerPreferenceDao = customerPreferenceDao;
- }
- <context:component-scan base-package="org.example"/> <!-- 检测这些类并注册-->
- <!-- @Component、 @Repository、@Service或 @Controller -->
- @Service("myMovieLister")
- public class SimpleMovieLister {
- // ...
- }
- @Repository
- public class MovieFinderImpl implements MovieFinder {
- // ...
- }
4、面向切面
添加jar包:
spring : spring-aop.jar、spring-aspects
aspect : aspectjrt.jar、aspectjtools.jar
item : aopalliance.jar
- <?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:aop="http://www.springframework.org/schema/aop"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
- <context:annotation-config />
- <context:component-scan base-package="com.itsoft"/>
- <aop:aspectj-autoproxy />
- </beans>
xml配置
- package com.itsoft;
- import org.aspectj.lang.ProceedingJoinPoint;
- import org.aspectj.lang.annotation.After;
- 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;
- /**
- *
- * @author Administrator
- * 通过aop拦截后执行具体操作
- */
- @Aspect
- @Component
- public class LogIntercept {
- @Pointcut("execution(public * com.itsoft.action..*.*(..))")
- public void recordLog(){}
- @Before("recordLog()")
- public void before() {
- this.printLog("已经记录下操作日志@Before 方法执行前");
- }
- @Around("recordLog()")
- public void around(ProceedingJoinPoint pjp) throws Throwable{
- this.printLog("已经记录下操作日志@Around 方法执行前");
- pjp.proceed();
- this.printLog("已经记录下操作日志@Around 方法执行后");
- }
- @After("recordLog()")
- public void after() {
- this.printLog("已经记录下操作日志@After 方法执行后");
- }
- private void printLog(String str){
- System.out.println(str);
- }
- }
aspect实现(@Around @Before @After)
- <bean id="logInterceptor" class="com.bjsxt.aop.LogInterceptor"></bean>
- <aop:config>
- <aop:aspect id="logAspect" ref="logInterceptor">
- <aop:before method="before" pointcut="execution(public * com.bjsxt.service..*.add(..))" />
- </aop:aspect>
- </aop:config>
XML替代注解
5、Spring 常用实现
- <bean id="propertyConfigurerForAnalysis" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="location">
- <value>classpath:com/foo/jdbc.properties</value>
- </property>
- </bean>
- <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="locations">
- <list>
- <value>classpath:/spring/include/jdbc-parms.properties</value>
- <value>classpath:/spring/include/base-config.properties</value>
- </list>
- </property>
- </bean>
- <context:property-placeholder location="classpath:com/foo/jdbc.properties"/> <!-- 简化 spring2.5 支持,多个以逗号(,)分开 -->
属性占位符PropertyPlaceholderConfigurer
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
- <!--Connection Info -->
- <property name="driverClassName" value="${jdbc.driver}" />
- <property name="url" value="${jdbc.url}" />
- <property name="username" value="${jdbc.username}" />
- <property name="password" value="${jdbc.password}" />
- <!--Connection Pooling Info -->
- <property name="initialSize" value="5" />
- <property name="maxActive" value="100" />
- <property name="maxIdle" value="30" />
- <property name="maxWait" value="10000" />
- <property name="poolPreparedStatements" value="true" />
- <property name="defaultAutoCommit" value="true" />
- </bean>
数据源配置,使用应用内的DBCP数据库连接池
- <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
- <property name="dataSource" ref="dataSource"/>
- </bean>
jdbcTemplate
- <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="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
- <property name="sessionFactory" ref="sessionFactory"></property>
- </bean>
hibernateTemplate、sessionFactory
- Xml
- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource"/>
- </bean>
- <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
- <property name="sessionFactory" ref="sessionFactory" />
- </bean>
- <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
- Java
- @Transactional(readOnly=true)
事务注解
- <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>
事务XML配置
- <filter>
- <filter-name>encodingFilter</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>GBK</param-value>
- </init-param>
- </filter>
编码设置CharacterEncodingFilter
- <filter>
- <filter-name>openSessionInView</filter-name>
- <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
- <init-param>
- <param-name>singleSession</param-name>
- <param-value>true</param-value>
- </init-param>
- <init-param>
- <param-name>sessionFactoryBeanName</param-name>
- <param-value>sf</param-value>
- </init-param>
- <init-param>
- <param-name>flushMode</param-name>
- <param-value>AUTO</param-value>
- </init-param>
- </filter>
发起一个页面请求时打开Hibernate的Session
三、实例化容器
1、java实例化容器
- ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/spring/products.xml");
2、web配置
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- <!-- default: /WEB-INF/applicationContext.xml -->
- </listener>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <!-- <param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value> -->
- <param-value>classpath:beans.xml</param-value>
- </context-param>
四、spring mvc
http://elf8848.iteye.com/blog/875830/
Spring使用总结的更多相关文章
- 基于spring注解AOP的异常处理
一.前言 项目刚刚开发的时候,并没有做好充足的准备.开发到一定程度的时候才会想到还有一些问题没有解决.就比如今天我要说的一个问题:异常的处理.写程序的时候一般都会通过try...catch...fin ...
- 玩转spring boot——快速开始
开发环境: IED环境:Eclipse JDK版本:1.8 maven版本:3.3.9 一.创建一个spring boot的mcv web应用程序 打开Eclipse,新建Maven项目 选择quic ...
- Spring基于AOP的事务管理
Spring基于AOP的事务管理 事务 事务是一系列动作,这一系列动作综合在一起组成一个完整的工作单元,如果有任何一个动作执行失败,那么事务 ...
- [Spring]IoC容器之进击的注解
先啰嗦两句: 第一次在博客园使用markdown编辑,感觉渲染样式差强人意,还是github的样式比较顺眼. 概述 Spring2.5 引入了注解. 于是,一个问题产生了:使用注解方式注入 JavaB ...
- 学习AOP之透过Spring的Ioc理解Advisor
花了几天时间来学习Spring,突然明白一个问题,就是看书不能让人理解Spring,一方面要结合使用场景,另一方面要阅读源代码,这种方式理解起来事半功倍.那看书有什么用呢?主要还是扩展视野,毕竟书是别 ...
- 学习AOP之深入一点Spring Aop
上一篇<学习AOP之认识一下SpringAOP>中大体的了解了代理.动态代理及SpringAop的知识.因为写的篇幅长了点所以还是再写一篇吧.接下来开始深入一点Spring aop的一些实 ...
- 学习AOP之认识一下Spring AOP
心碎之事 要说知道AOP这个词倒是很久很久以前了,但是直到今天我也不敢说非常的理解它,其中的各种概念即抽象又太拗口. 在几次面试中都被问及AOP,但是真的没有答上来,或者都在面上,这给面试官的感觉就是 ...
- 为什么做java的web开发我们会使用struts2,springMVC和spring这样的框架?
今年我一直在思考web开发里的前后端分离的问题,到了现在也颇有点心得了,随着这个问题的深入,再加以现在公司很多web项目的控制层的技术框架由struts2迁移到springMVC,我突然有了一个新的疑 ...
- Spring之旅(2)
Spring简化Java的下一个理念:基于切面的声明式编程 3.应用切面 依赖注入的目的是让相互协作的组件保持松散耦合:而AOP编程允许你把遍布应用各处的功能分离出来形成可重用的组件. AOP面向切面 ...
- Spring之旅
Java使得以模块化构建复杂应用系统成为可能,它为Applet而来,但为组件化而留. Spring是一个开源的框架,最早由Rod Johnson创建.Spring是为了解决企业级应用开发的复杂性而创建 ...
随机推荐
- WinForms 新窗体后台打开完美的解决
最近在做浏览器开发时,想要实现 IE 6那种多窗体,又允许后台打开而不抢占视野的方式. WinForms 应用程序中想要后台打开一个新的窗体,而不(抢焦).(遮挡)目前窗体. 需要注意的是,SW_SH ...
- WCF与WebService之间的异同
下面我们来详细讨论一下二者的区别.Web Service和WCF的到底有什么区别. 1,Web Service:严格来说是行业标准,也就是Web Service 规范,也称作WS-*规范,既不是框架, ...
- Spring生态
1.简洁有力,干掉了j2ee容器层特别是ejb,spring在rod Johnson十几年前一个人单挑j2ee体系开始,到十年前开始大行其道至今,基本上是java开发领域的事实标准.从此大部分开发者去 ...
- 创建MySQL从库
我们知道Oracle有DataGuard实时备份数据.能够做主备切换,而MySQL也有自己的一套备库方案.称之为主从复制. 搭建MySQL从库是为了实时同步主库数据,同一时候也能够分担主库的读压力.对 ...
- uint8_t / uint16_t / uint32_t /uint64_t 是什么数据类型(转)
在nesc的代码中,你会看到很多你不认识的数据类型,比如uint8_t等.咋一看, 好像是个新的数据类型,不过C语言(nesc是C的扩展)里面好像没有这种数据类型啊!怎么又是u又是_t的?很多人有这样 ...
- PHP生成条形码
前阵子在做一个商家优惠券的功能,需要用到条形码,于是将资料重新整理下. 1.什么是条形码? 百度百科定义:条形码(barcode)是将宽度不等的多个黑条和空白,按照一定的编码规则排列,用以表达一组信息 ...
- LINUX命令之ETHTOOL用法详解
转载:http://crazyming.blog.51cto.com/1048571/738022 debian 下安装: sudo apt-get install ethtool 或者下载源码编译: ...
- vb.net向Excel中写入值
根据网上例子结合自己的工具环境修改后测试可以通过 我使用的工具:Microsoft Visual Studio 2010,Excel 2007 一.在D盘新建一个temp文件夹用于存放Excel启动时 ...
- CCTableView的使用和注意事项
#include "cocos-ext.h" using namespace cocos2d::extension; class TableViewTestLayer: publi ...
- 前端必会html知识整理
1.浏览器内核: 1.ie:trident(三叉戟)内核 2.firefox:gecko(壁虎)内核 3.safari:webkit(浏览器核心)内核 ...