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是为了解决企业级应用开发的复杂性而创建 ...
随机推荐
- lua入门
print("hello lua") lua官网 在线运行代码 数据类型 数据类型 描述 number 数字,可当作double,5/2 == 2.5 string 字符串 nil ...
- 最长不下降子序列nlogn算法详解
今天花了很长时间终于弄懂了这个算法……毕竟找一个好的讲解真的太难了,所以励志我要自己写一个好的讲解QAQ 这篇文章是在懂了这个问题n^2解决方案的基础上学习. 解决的问题:给定一个序列,求最长不下降子 ...
- Linux下的C高级编程---学习
一.进程 一个正在运行的程序称为进程.例如在屏幕上正打开两个终端窗口,则说明同一个终端程序正在做为两个进程而同时执行,而每个终端窗口又都在执行shell,则每个shell又是另外一个进程 ...
- 查看数量linux下查看cpu物理个数和逻辑个数
首先声明,我是一个菜鸟.一下文章中出现技术误导情况盖不负责 hadoop@chw-desktop3:~$ cat /proc/cpuinfo processor : 0 vendor_id : Gen ...
- iOS开发——实用篇Swift篇&项目开发常用实用技术
项目开发常用实用技术 实现拨打电话 要实现打电话功能,最简单最直接的方式便是:直接跳到拨号界面 (注意:这个需要真机调试,模拟器无效果) UIApplication.sharedApplica ...
- Android Configuration change属性
问题:横竖屏切换时Activity的生命周期? 答案: 1.不设置Activity的android:configChanges时,切屏会重新调用各个生命周期,切横屏时会执行一次,切竖屏时会执行两次 2 ...
- JavaScript提高:003:easy UI实现tab页面自适应问题
前面说到使用easyUI在asp.net中实现了tab控件效果.http://blog.csdn.net/yysyangyangyangshan/article/details/38307477只是有 ...
- hdu 3849 (双联通求桥)
一道简单的双联通求桥的题目,,数据时字符串,,map用的不熟练啊,,,,,,,,,,,,, #include <iostream> #include <cstring> #in ...
- NetBeans 安装Android 开发环境
基本的开发环境都是Eclipse + Android SDK + Android plugin for Eclipse NetBeans下开发Android的所需要的基本条件:NetBeans(包含J ...
- org.apache.hadoop.fs-BufferedFSInputStream
封装了FSInputStream package org.apache.hadoop.fs; import java.io.BufferedInputStream; import java.io.IO ...