Spring使用总结

一、基础JAR包

spring-beans.jar spring-context.jar spring-core.jar spring-expression.jar

二、XML的配置

1、一级结构

1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4        xsi:schemaLocation="http://www.springframework.org/schema/beans
5            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
6   <bean id="..." class="...">
7     <!-- collaborators and configuration for this bean go here -->
8   </bean>
9 </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/> <!-- 集合 对应ListSetMapProperties的值-->

3、注解

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xsi:schemaLocation="http://www.springframework.org/schema/beans 
 6            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 7            http://www.springframework.org/schema/context
 8            http://www.springframework.org/schema/context/spring-context-2.5.xsd">
 9                
10      <context:annotation-config/>
11      
12 </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

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4       xmlns:aop="http://www.springframework.org/schema/aop"
 5       xmlns:context="http://www.springframework.org/schema/context"
 6       xsi:schemaLocation="
 7        http://www.springframework.org/schema/context
 8        http://www.springframework.org/schema/context/spring-context-3.0.xsd
 9        http://www.springframework.org/schema/beans 
10        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
11        http://www.springframework.org/schema/aop 
12        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
13     <context:annotation-config />
14     <context:component-scan base-package="com.itsoft"/>
15     <aop:aspectj-autoproxy />
16 </beans>
xml配置
 1 package com.itsoft;
 2 
 3 import org.aspectj.lang.ProceedingJoinPoint;
 4 import org.aspectj.lang.annotation.After;
 5 import org.aspectj.lang.annotation.Around;
 6 import org.aspectj.lang.annotation.Aspect;
 7 import org.aspectj.lang.annotation.Before;
 8 import org.aspectj.lang.annotation.Pointcut;
 9 import org.springframework.stereotype.Component;
10 
11 /**
12  * 
13  * @author Administrator
14  * 通过aop拦截后执行具体操作
15  */
16 @Aspect
17 @Component
18 public class LogIntercept {
19 
20     @Pointcut("execution(public * com.itsoft.action..*.*(..))")
21     public void recordLog(){}
22 
23     @Before("recordLog()")
24     public void before() {
25         this.printLog("已经记录下操作日志@Before 方法执行前");
26     }
27 
28     @Around("recordLog()")
29     public void around(ProceedingJoinPoint pjp) throws Throwable{
30         this.printLog("已经记录下操作日志@Around 方法执行前");
31         pjp.proceed();
32         this.printLog("已经记录下操作日志@Around 方法执行后");
33     }
34 
35     @After("recordLog()")
36     public void after() {
37         this.printLog("已经记录下操作日志@After 方法执行后");
38     }
39 
40     private void printLog(String str){
41         System.out.println(str);
42     }
43 }
aspect实现(@Around @Before @After)
1 <bean id="logInterceptor" class="com.bjsxt.aop.LogInterceptor"></bean>
2 <aop:config>
3     <aop:aspect id="logAspect" ref="logInterceptor">
4     <aop:before method="before" pointcut="execution(public * com.bjsxt.service..*.add(..))" />
5     </aop:aspect>
6 </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
 1 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
 2          <!--Connection Info -->
 3         <property name="driverClassName" value="${jdbc.driver}" />
 4         <property name="url" value="${jdbc.url}" />
 5         <property name="username" value="${jdbc.username}" />
 6         <property name="password" value="${jdbc.password}" />
 7 
 8          <!--Connection Pooling Info -->
 9         <property name="initialSize" value="5" />
10         <property name="maxActive" value="100" />
11         <property name="maxIdle" value="30" />
12         <property name="maxWait" value="10000" />
13         <property name="poolPreparedStatements" value="true" />
14         <property name="defaultAutoCommit" value="true" />
15     </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
 1 Xml
 2 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 3     <property name="dataSource" ref="dataSource"/>
 4 </bean>
 5 
 6 <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
 7     <property name="sessionFactory" ref="sessionFactory" />
 8 </bean>
 9 
10 <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
11 
12 Java
13 @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
 1 <filter>
 2         <filter-name>openSessionInView</filter-name>
 3         <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
 4         <init-param>
 5                     <param-name>singleSession</param-name>
 6                     <param-value>true</param-value>
 7             </init-param>
 8         <init-param>
 9             <param-name>sessionFactoryBeanName</param-name>
10             <param-value>sf</param-value>
11         </init-param>
12         <init-param>
13                     <param-name>flushMode</param-name> 
14                     <param-value>AUTO</param-value>
15             </init-param>
16     </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/

原文地址:https://www.cnblogs.com/Nadim/p/4724875.html