一、基础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使用总结的更多相关文章

  1. 基于spring注解AOP的异常处理

    一.前言 项目刚刚开发的时候,并没有做好充足的准备.开发到一定程度的时候才会想到还有一些问题没有解决.就比如今天我要说的一个问题:异常的处理.写程序的时候一般都会通过try...catch...fin ...

  2. 玩转spring boot——快速开始

    开发环境: IED环境:Eclipse JDK版本:1.8 maven版本:3.3.9 一.创建一个spring boot的mcv web应用程序 打开Eclipse,新建Maven项目 选择quic ...

  3. Spring基于AOP的事务管理

                                  Spring基于AOP的事务管理 事务 事务是一系列动作,这一系列动作综合在一起组成一个完整的工作单元,如果有任何一个动作执行失败,那么事务 ...

  4. [Spring]IoC容器之进击的注解

    先啰嗦两句: 第一次在博客园使用markdown编辑,感觉渲染样式差强人意,还是github的样式比较顺眼. 概述 Spring2.5 引入了注解. 于是,一个问题产生了:使用注解方式注入 JavaB ...

  5. 学习AOP之透过Spring的Ioc理解Advisor

    花了几天时间来学习Spring,突然明白一个问题,就是看书不能让人理解Spring,一方面要结合使用场景,另一方面要阅读源代码,这种方式理解起来事半功倍.那看书有什么用呢?主要还是扩展视野,毕竟书是别 ...

  6. 学习AOP之深入一点Spring Aop

    上一篇<学习AOP之认识一下SpringAOP>中大体的了解了代理.动态代理及SpringAop的知识.因为写的篇幅长了点所以还是再写一篇吧.接下来开始深入一点Spring aop的一些实 ...

  7. 学习AOP之认识一下Spring AOP

    心碎之事 要说知道AOP这个词倒是很久很久以前了,但是直到今天我也不敢说非常的理解它,其中的各种概念即抽象又太拗口. 在几次面试中都被问及AOP,但是真的没有答上来,或者都在面上,这给面试官的感觉就是 ...

  8. 为什么做java的web开发我们会使用struts2,springMVC和spring这样的框架?

    今年我一直在思考web开发里的前后端分离的问题,到了现在也颇有点心得了,随着这个问题的深入,再加以现在公司很多web项目的控制层的技术框架由struts2迁移到springMVC,我突然有了一个新的疑 ...

  9. Spring之旅(2)

    Spring简化Java的下一个理念:基于切面的声明式编程 3.应用切面 依赖注入的目的是让相互协作的组件保持松散耦合:而AOP编程允许你把遍布应用各处的功能分离出来形成可重用的组件. AOP面向切面 ...

  10. Spring之旅

    Java使得以模块化构建复杂应用系统成为可能,它为Applet而来,但为组件化而留. Spring是一个开源的框架,最早由Rod Johnson创建.Spring是为了解决企业级应用开发的复杂性而创建 ...

随机推荐

  1. 字符串匹配 - KMP算法

    #include<cstdio> #include<cstring> #include<cstdlib> void GetNext(char *t,int *nex ...

  2. Codeforces Gym 100650B Countdown DFS

    Problem B: CountdownTime Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hust.edu.cn/vjudge/conte ...

  3. 深度学习论文笔记-Deep Learning Face Representation from Predicting 10,000 Classes

    来自:CVPR 2014   作者:Yi Sun ,Xiaogang Wang,Xiaoao Tang 题目:Deep Learning Face Representation from Predic ...

  4. iOS开发——总结篇&常用开发总结

    一.通知1.监听通知 - (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(i ...

  5. Online Schema Upgrade in MySQL Galera Cluster using TOI Method

    http://severalnines.com/blog/online-schema-upgrade-mysql-galera-cluster-using-toi-method     As a fo ...

  6. DataPackage-数据库、表的区域设置和系统不一致导致处理失败

    问题描述:       最近学习Datapackage,创建完之后,部署处理但总是提示某某字段的区域设置和目标字段的区域设置不一致,具体如图:             测试发现其它的数据库表又没有这类 ...

  7. c#智能感知(设置)及实现

    1) 使用工具->选项菜单命令,选择文本编辑器->C#设置, 将上面圈出的2个复选框(自动列出成员和参数信息)打勾, 然后 Intellisense就会工作了.(如果没这么多选项,请勾选S ...

  8. Debian5.04安装oracle11g 笔记

    新安装了Debian5,成功安装了oracle11g.记录过程如下. 1.升级一下系统    #apt-get update    #apt-get upgrade 2.安装需要的一些组件:    # ...

  9. Scala中的构造器

    Scala中的构造器 Scala中的构造器分为两类,主构造器和辅助构造器 主构造器是通过类名后面跟的括号里加参数列表来定义 辅助构造器是通过关键字this定义 定义一个无参主构造器 class rec ...

  10. Getting Started with Zend Framework MVC Applications

    Getting Started with Zend Framework MVC Applications This tutorial is intended to give an introducti ...