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是为了解决企业级应用开发的复杂性而创建 ...
随机推荐
- wikioi 3116 高精度练习之加法
题目描述 Description 给出两个正整数A和B,计算A+B的值.保证A和B的位数不超过500位. 输入描述 Input Description 读入两个用空格隔开的正整数 输出描述 Outpu ...
- android SoundPool播放音效
MediaPlayer的缺点: 资源占用量高,延时时间较长 不支持多个音效同一时候播放 SoundPool主要用于播放一些较短的声音片段,CPU资源占用率低和反应延时小,还支持自行色设置声音的品质,音 ...
- URAL 1775 B - Space Bowling 计算几何
B - Space BowlingTime Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hust.edu.cn/vjudge/contest/ ...
- OpenCV 2.2版本号以上显示图片到 MFC 的 Picture Control 控件中
OpenCV 2.2 以及后面的版本号取消掉了 CvvImage.h 和CvvImage.cpp 两个文件,直接导致了苦逼的程序猿无法调用里面的显示函数来将图片显示到 MFC 的 Picture Co ...
- iOS开发——UI篇OC篇&UIView/UIWindow/UIScreen/CALayer
UIView/UIWindow/UIScreen/CALayer 1.UIScreen可以获取设备屏幕的大小. 1 2 3 4 5 6 7 // 整个屏幕的大小 {{0, 0}, {320, 480} ...
- Word2010编号列表&多级列表
1.引用场景 对于一份标准.漂亮的word文档,编号列表和多级列表的设置时必不可少的,正因为有它们,文档看起来才更专业,使用起来才更加的方便.如下面截图一般,这是十分常见的多级列表设置 ...
- "jobTracker is not yet running"(hadoop 配置)
今天自己尝试做配置了一下hadoop,环境是ubuntu13.10+jdk1.7.0_51+hadoop version1.2.1. 主要过程主要参考http://blog.csdn.net/hitw ...
- PhpCMS标签:专题模块special标签
专题模块 专题模块PC标签调用说明 模块名:special 模块提供的可用操作 操作名 说明 lists 专题列表 content_list 专题信息列表 hits 专题信息点击排序 下面对所有的操作 ...
- Linux命令行技巧
Linux命令行技巧 命令 描述 • apropos whatis 显示和word相关的命令. 参见线程安全 • man -t man | ps2pdf - > man.pdf 生成一个PDF格 ...
- [课程相关]homework-05
零.准备工作 队伍成员:梁杰,夏天晗,谢祖三. 周五晚上吃完饭,我们就开始了讨论. 这次的要求是写服务器,客户端以及游戏结果动态显示.很明显是三个部分,我们也就顺其自然, 一人一个部分.我负责服务器, ...