spring

spring4介紹

歷史
    2002年仪搔,Rod Johnson寫了一本書斗塘,對(duì)以EJB為核心的Java EE平臺(tái)進(jìn)行批評(píng)和思考。
    2003年屠阻,Rod Johnson開發(fā)了一個(gè)框架宴树,這就是Spring策菜。Spring的很多設(shè)計(jì)理念,其實(shí)就是起源EJB的啟發(fā)酒贬。
    當(dāng)然又憨,Spring更加簡(jiǎn)單易用。
項(xiàng)目中間層
    ssh: Spring Struts2 Hibernate/ssm: Spring SpringMVC MyBatis
    Spring(沒有代替框架)
下載
    官方網(wǎng)站
        http://www.springsource.org
    下載倉庫地址
        http://repo.springsource.org/libs-release-local/org/springframework/spring/
    maven
        搜索spring即可
目錄介紹
    docs 
        api文檔與開發(fā)指南
    libs 
        所有模塊的jar包
    schema 
        xml的約束文件
使用步驟
    1.拷貝jar (20個(gè)) + common-logging-xx.jar
        libs下的jar包
    2.寫appContext.xml配置文件
        docs\spring-framework-reference\index.html\Core\Configuration metadata
        拷貝xml基礎(chǔ)配置
    3.獲取Spring容器
        ClassPathXmlApplicationContext (class路徑下找配置文件)
        FileSystemXmlApplicationContext (磁盤目錄下找配置文件)
    4.到Spring容器中獲取bean
    5.關(guān)閉Spring容器
注意
    spring4使用jdk7
    spring5使用jdk8
得到spring容器兩種方式
    第一種方式
        src/appContext.xml
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appContext.xml");
        User user = (User)context.getBean("user");
        context.close();
    第二種方式
        src/appContext.xml
        //FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("D:\\myselfwork1\\SpringTest\\src\\appContext.xml");
        FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("classpath:appContext.xml");
        User user = (User)context.getBean("user");
        System.out.println(user);
        context.close();

spring配置詳解

beans
    根元素,配置全局屬性
    對(duì)所有的bean子元素起作用
    屬性
        default-lazy-init 否默認(rèn)延遲初始化bean
bean
    驅(qū)動(dòng)類的構(gòu)造器創(chuàng)建實(shí)例
    指定自己的相關(guān)的屬性
    屬性
        id 唯一標(biāo)識(shí)符
        class 指定類(包名+類名)
        lazy-init 延遲初始化
        abstract 抽象類,true:Spring容器不會(huì)初始化,可以不用寫class屬性
    子標(biāo)簽
        constructor-arg 指定構(gòu)造器中的參數(shù)(有參數(shù)的構(gòu)造器)
        property 驅(qū)動(dòng)setter方法設(shè)置參數(shù)
        constructor-arg說明
            <bean id="user" class="com.shuai.domain.User"></bean>
                調(diào)用的是無參構(gòu)造public User() {}
            <bean id="user" class="com.shuai.domain.User">
                <constructor-arg><value type="java.lang.String">帥哥</value></constructor-arg>
            </bean>
                調(diào)用的是有參構(gòu)造public User(String name) {}
            <bean id="user" class="com.shuai.domain.User">
                <constructor-arg><value type="java.lang.String">帥哥</value></constructor-arg>
                <constructor-arg><value type="int">20</value></constructor-arg>
            </bean>
                調(diào)用的是有參構(gòu)造public User(String name, int age) {}
        property說明
            <bean id="user" class="com.shuai.domain.User">
                <property name="name"><value type="java.lang.String">帥哥</value></property>
            </bean>
                調(diào)用的是setter方法public void setName(String name) {}

IOC(控制反轉(zhuǎn)) 與 DI(依賴注入)重點(diǎn)

IOC
    Inversion of Control
    控制反轉(zhuǎn)
    對(duì)象的創(chuàng)建交給Spring去做.
    B類需要一個(gè)A類對(duì)象,按照慣例B類自己new一個(gè)A類對(duì)象.由B來控制A是否被創(chuàng)建.但是現(xiàn)在對(duì)象的創(chuàng)建交給Spring做了,那么控制關(guān)系就反過來了,稱為控制反轉(zhuǎn).
DI
    Dependecy Injection
    依賴注入
    B類需要一個(gè)A類對(duì)象,只能接受Spring容器的注入.
    從容器角度來看,容器將A對(duì)象注入到B類中,就稱為依賴注入

依賴注入各種類型constructor-arg/property

constructor-arg屬性
    value 可以傳入8種基本數(shù)據(jù)類型/基本數(shù)據(jù)類型包裝類/字符串
    ref 引用容器中的bean實(shí)例
    type 數(shù)據(jù)類型
    index 在構(gòu)造函數(shù)中的位置
    name 構(gòu)造函數(shù)中的名字
value標(biāo)簽
    8種基本數(shù)據(jù)類型(byte/short/int/long/float/double/char/boolean)
        <value type="byte">1</value>
        public User(byte b) {}
    基本數(shù)據(jù)類型包裝類(Byte,Short,Integer,Long,Float,Double,Character,Boolean)
        <value type="java.lang.Byte">1</value>
        public User(Byte b) {}
    字符串(String)
        <value type="java.lang.String">帥哥</value>
        public User(String b) {}
array標(biāo)簽
    value-type 數(shù)據(jù)類型 默認(rèn)是String類型
        <array value-type="java.lang.String">
            <value>aa</value><value>bb</value>
        </array>
        public User(String[] arr) {}
list標(biāo)簽
    value-type 數(shù)據(jù)類型 默認(rèn)是String類型
        <list value-type="java.lang.String">
            <value>a</value><value>10</value>
        </list>
        public User(List<String> list) {}
set標(biāo)簽
    value-type 數(shù)據(jù)類型 默認(rèn)是String類型
        <set value-type="java.lang.String">
            <value>aa</value><value>bb</value>
        </set>
        public User(Set<String> set) {}
map標(biāo)簽
    value-type 數(shù)據(jù)類型 默認(rèn)是String類型
        <map><entry key="aa" value="bb"></entry></map>
        public User(Map<String,String> map) {}
props標(biāo)簽
    value-type 數(shù)據(jù)類型 默認(rèn)是String類型
        <props><prop key="url">xx</prop></props>
        public User(Properties prop) {}
bean標(biāo)簽
    <bean class="java.util.Date"/>
    public User(Date date) {}
ref標(biāo)簽
    引用容器中的bean實(shí)例
    <bean id="date" class="java.util.Date"/>
    <ref bean="date"/>
    public User(Date date) {}
idref標(biāo)簽
    引用bean的id是一個(gè)字符串
    public User(Date date) {}

配置別名

第一種方式
    <bean id="user" name="user2,user3" class=""/>
    <bean id="user" name="user2 user3" class=""/>
第二種方式
    <bean id="user" class=""/>
    <alias name="user" alias="user1"/>

導(dǎo)入其它配置文件

src/appContext-service.xml
<import resource="appContext-service.xml"/>

bean的作用域

singleton
    單例
    Spring容器中的實(shí)例都默認(rèn)單例
prototype
    不會(huì)預(yù)初始化,每次都會(huì)創(chuàng)建一個(gè)新實(shí)例
request
    對(duì)應(yīng)Web應(yīng)用request作用域
session
    對(duì)應(yīng)Web應(yīng)用session作用域
application
    對(duì)應(yīng)Web應(yīng)用application作用域
websocket
    Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext
globalSession
    Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a Portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

bean中獲取Spring容器

public class User implements ApplicationContextAware{
    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {}
}

p調(diào)用屬性set方法賦值命名空間

在配置文件中增加一行 xmlns:p="http://www.springframework.org/schema/p"
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans.xsd">
        <bean id="date" class="java.util.Date"/>
        <bean id="user" class="com.shuai.domain.User" 
            p:name="shuaige"
            p:date-ref="date"></bean>
    </beans>
    public class User{
        private String name;
        private Date date;
        getter/setter..
    }
注意:
    p:set方法名去掉前面的set后首字母小寫=值(標(biāo)量類型)

自動(dòng)裝配(bean的autowire屬性)??????

說明
    autowire 自動(dòng)裝配(有4種裝配方式)
    autowire-candidate 是否作為自動(dòng)裝配的候選者
byName
    按名稱自動(dòng)裝配
    <bean id="idCard" class="com.shuai.domain.IdCard"/>    
    <bean id="user" class="com.shuai.domain.User" autowire="byName"/>
    public class User{
        private IdCard idCard;
        getter/setter..
    }
byType
    按類型自動(dòng)裝配
    <bean id="idCard" class="com.shuai.domain.IdCard" autowire-candidate="true"/>    
    <bean id="user" class="com.shuai.domain.User" autowire="byType"/>
    public class User{
        private IdCard idCard;
        getter/setter..
    }
constructor
    按構(gòu)造器自動(dòng)裝配,按照構(gòu)造器中的形參的名字來選擇bean的id名
    <bean id="idCard" class="com.shuai.domain.IdCard" autowire-candidate="true"/> 
    <bean id="user" class="com.shuai.domain.User" autowire="constructor"/>
    public class User{
        private IdCard idCard;
        public User(IdCard idCard) {
            this.idCard = idCard;
        }
    }
no
    不自動(dòng)裝配
default

c調(diào)用構(gòu)造器賦值屬性命名空間

在配置文件中增加一行 xmlns:c="http://www.springframework.org/schema/c"
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:c="http://www.springframework.org/schema/c"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans.xsd">
        <bean id="date" class="java.util.Date"/>
        <bean id="user" class="com.shuai.domain.User" 
            c:_0="帥哥"
            c:_1-ref="date"></bean>
    </beans>
    public class User{
        private String name;
        private Date date;
        public User(String name,Date date){}
    }
注意:
    p:set方法名去掉前面的set后首字母小寫=值(標(biāo)量類型)

Bean創(chuàng)建的三種方式

第一種方式
    構(gòu)造器方式
    <bean id="user" class="com.shuai.domain.User"></bean>
第二種方式
    調(diào)用靜態(tài)工廠方法創(chuàng)建Bean
    <bean id="user" class="com.shuai.domain.UserFactory" factory-method="createUser"></bean>
    public class UserFactory {
        public static User createUser(){
            return new User();
        }
    }
第三種方式
    調(diào)用實(shí)例工廠方法創(chuàng)建Bean
    <bean id="userFactory" class="com.shuai.domain.UserFactory"></bean>
    <bean id="user" factory-bean="userFactory" factory-method="createUser"></bean>
    public class UserFactory {
        public User createUser(){
            return new User();
        }
    }

繼承配置

配置文件
    <bean id="human" abstract="true" p:name="shuaige"></bean>
    <bean id="user" class="com.shuai.domain.User" parent="human"></bean>
User.java
    public class User{
        private String name;
        getter/setter..
    }
注意:
    1.會(huì)自動(dòng)給User類的name屬性賦值,因?yàn)楦割惒淮嬖?    2.父類Bean必須是一個(gè)抽象的Bean

Bean的生命周期

第一種方式
    init-method 屬性
        初始化方法,創(chuàng)建對(duì)象時(shí),會(huì)主動(dòng)調(diào)用此方法
        <bean id="user" class="" init-method="init"/>
        public void init(){}
    destroy-method 屬性
        銷毀方法,在對(duì)象銷毀之前會(huì)執(zhí)行此方法
        <bean id="user" class=""destroy-method="destroy"/>
        public void destroy(){}
第二種方式
    InitializingBean 接口
        初始化接口
        創(chuàng)建對(duì)象時(shí),會(huì)主動(dòng)調(diào)用此接口的方法
        public class User implements InitializingBean{
            @Override
            public void afterPropertiesSet() throws Exception {}
        }
    DisposableBean 接口
        銷毀接口,在對(duì)象銷毀之前會(huì)執(zhí)行此接口的方法
        public class User implements DisposableBean{
            @Override
            public void destroy() throws Exception {}
        }

調(diào)用get方法(PropertyPathFactoryBean)

配置
    <bean id="user" class="com.shuai.domain.User" p:name="帥哥" p:age="20"></bean>
    <bean id="getUsername" class="org.springframework.beans.factory.config.PropertyPathFactoryBean" p:targetObject-ref="user" p:propertyPath="name"/>
    <bean id="getUserage" class="org.springframework.beans.factory.config.PropertyPathFactoryBean" p:targetBeanName="user" p:propertyPath="age"/>
User.java
    public class User{
        private String name;
        get/set..
    }
獲取
    String name = (String)context.getBean("getUsername");
    Integer age = (Integer)context.getBean("getUserage");

調(diào)用普通方法(MethodInvokingFactoryBean)

調(diào)用無參無返回值方法
    <bean id="invokeSay" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" p:targetObject-ref="user" p:targetMethod="say"/>
調(diào)用有參無返回值方法
    <bean id="invokeSayWord" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" p:targetObject-ref="user" p:targetMethod="sayword">
        <property name="arguments"><value>hi</value></property>
    </bean>
    注意:
        1.arguments是固定的,相當(dāng)于一個(gè)數(shù)組,對(duì)應(yīng)方法的形參列表
        2.傳值要按照順序去傳即可
調(diào)用無參又返回值
    <bean id="invokeSay" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" p:targetObject-ref="user" p:targetMethod="say"/>
    String backStr = (String)context.getBean("invokeSay");

調(diào)用靜態(tài)方法(MethodInvokingFactoryBean)

調(diào)用無參無返回值靜態(tài)方法
    <bean id="invokeHi" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" p:targetClass="com.shuai.domain.User" p:targetMethod="hi"/>
    <bean id="invokeHi" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" p:staticMethod="com.shuai.domain.User.hi"/>
帶參數(shù)的同上調(diào)用普通方法

獲取類中公共的靜態(tài)常量(FieldRetrievingFactoryBean)

配置
    <bean id="table" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean" p:staticField="com.shuai.domain.User.TABLE"/>
    <bean id="table" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean" p:targetClass="com.shuai.domain.User" p:targetField="TABLE"/>
User.java
    public class User{
        public static final String TABLE = "user";
    }
調(diào)用
    String table = (String)context.getBean("table");

獲取對(duì)象的屬性(FieldRetrievingFactoryBean)

配置
    <bean id="user" class="com.shuai.domain.User" p:name="帥哥"></bean>
    <bean id="username" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean" p:targetObject-ref="user" p:targetField="name"/>
User.java
    public class User{
        public String name;
    }
獲取
    String name = (String)context.getBean("username");
注意:
    用的很少,會(huì)破壞我們的封裝,不匹配POJO原則

util命名空間

說明
    IOC配置方式簡(jiǎn)化
    基于Schema簡(jiǎn)化
    引入
        添加xmlns:util="http://www.springframework.org/schema/util" ,并且引入spring-util-4.2.xsd文件
    標(biāo)簽
        util:constant 簡(jiǎn)化訪問靜態(tài)的Field
        util:property-path 簡(jiǎn)化get方法調(diào)用
        util:list 配置List集合
        util:set 配置Set集合
        util:map 配置Map集合
        util:properties 配置Properties集合
引入
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
                        http://www.springframework.org/schema/util
                        http://www.springframework.org/schema/util/spring-util-4.2.xsd"></beans>
util:constant
    <util:constant id="table" static-field="com.shuai.domain.User.TABLE"/>
    String table = (String)context.getBean("table");
util:property-path
    <bean id="user" class="com.shuai.domain.User" p:name="帥哥"></bean>
    <util:property-path id="name" path="user.name"/>
    String name = (String)context.getBean("name");
util:list
    <util:list id="list">
        <value>11</value>
        <value>22</value>
    </util:list>
    <bean id="user" class="com.shuai.domain.User" c:_0-ref="list"></bean>
    public class User {
        private List<String> list;
        public User(List<String> list) {}
    }
util:set
    <bean id="user" class="com.shuai.domain.User" c:_0-ref="set"></bean>
    <util:set id="set">
        <value>11</value>
        <value>22</value>
    </util:set>
    public class User {
        private Set<String> set;
        public User(Set<String> set) {}
    }
util:map
    <bean id="user" class="com.shuai.domain.User" c:_0-ref="map"></bean>
    <util:map id="map">
        <entry key="name" value="帥哥"></entry>
        <entry key="age" value="20"></entry>
    </util:map>
    public class User {
        private Map<String,String> map;
        public User(Map<String,String> map) {}
    }
util:properties
    <bean id="user" class="com.shuai.domain.User" c:_0-ref="prop"></bean>
    <util:properties id="prop">
        <prop key="username">root</prop>
        <prop key="password">root</prop>
    </util:properties>
    public class User {
        private Properties prop;
        public User(Properties prop) {}
    }

SpEL表達(dá)式

概述
    Spring Expression Language
    Spring表達(dá)式語言
    API
        ExpressionParser
            Spring表達(dá)式解析器 
        EvaluationContext
            Spring容器
運(yùn)算表達(dá)式
    ExpressionParser parser = new SpelExpressionParser();
    //表達(dá)式
    String str = "10+10";
    //解析表達(dá)式
    Expression expression = parser.parseExpression(str);
    //得到結(jié)果
    Object value = expression.getValue();
    int value1 = expression.getValue(Integer.class);
字符串
    String str = parser.parseExpression("Spring").getValue(String.class);
字符串長(zhǎng)度
    Object strlength = parser.parseExpression("'Spring'.bytes.length").getValue();
定義數(shù)組
    String[] arr = (String[])parser.parseExpression("new String[]{'Spring','mybatis'}").getValue();
定義List集合
    List<Object> list = (List<Object>)parser.parseExpression("{'spring',100}").getValue();
定義Map集合
    Map<Object,Object> map = (Map<Object,Object>)parser.parseExpression("{'1':'shuaige,'2':20}").getValue();
調(diào)用類的靜態(tài)方法
    parser.parseExpression("T(java.lang.Math).random()").getValue();
    parser.parseExpression("T(java.lang.System).out.println('shuaige')").getValue();
創(chuàng)建類的對(duì)象,并且放入容器
    ExpressionParser parser = new SpelExpressionParser();
    EvaluationContext context = new StandardEvaluationContext();
    Object date = parser.parseExpression("new java.util.Date()").getValue();
    context.setVariable("date", date);
    Object longTime = parser.parseExpression("date.getTime()").getValue(context);
集合內(nèi)數(shù)據(jù)操作
    迭代
        ExpressionParser parser = new SpelExpressionParser();
        EvaluationContext context = new StandardEvaluationContext();
        context.setVariable("list", parser.parseExpression("{'SpringMvc','Spring','Hibernate'}").getValue());
        parser.parseExpression("list.?[length()>6]").getValue(context);
    字符串長(zhǎng)度
        ExpressionParser parser = new SpelExpressionParser();
        EvaluationContext context = new StandardEvaluationContext();
        context.setVariable("list", parser.parseExpression("{'SpringMvc','Spring','Hibernate'}").getValue());
        parser.parseExpression("#list.![length()]").getValue(context);
配置文件中使用
    List集合
        <bean id="user" class="com.shuai.domain.User" p:list="#{{'springmvc','spring'}}" />
    set集合
        <bean id="user" class="com.shuai.domain.User" p:set="#{{20,30}}" />
    map集合
        <bean id="user" class="com.shuai.domain.User" p:map="#{{'name':'帥哥','age':20}}" />
    properties
        <bean id="user" class="com.shuai.domain.User" p:prop="#{{'city':'廣州','name':'帥哥'}}" />
    數(shù)組
        <bean id="user" class="com.shuai.domain.User" p:arr="#{new String[]{'spring','hibernate'}}" />
    對(duì)象
        <bean id="user" class="com.shuai.domain.User" p:date="#{new java.util.Date()}" />
    調(diào)用靜態(tài)方法賦值
        <bean id="user" class="com.shuai.domain.User" p:result="#{T(com.shuai.domain.ResultUtil).sum(10,20)}" />

Spring資源訪問

第一種方式:配置文件
    單個(gè)文件
        文件
            src/db.properties
        配置
            <bean id="user" class="com.shuai.domain.User" p:resource="classpath:db.properties"/>
        User.java
            public class User {
                private Resource resource;
                get/set..
            }
    多個(gè)文件
        文件
            src/db.properties 和 src/log.properties
        配置
            <bean id="user" class="com.shuai.domain.User" p:resources="#{new Object[]{'classpath:db.properties','classpath:log.properties'}}"/>
        User.java
            public class User {
                private Resource[] resources;
            }
第二種方式:代碼
    文件
        src/db.properties
    代碼
        Resource resource = new ClassPathResource("db.properties");
        Resource resource = new FileSystemResource("D:\\workspace\\SpringTest\\src\\db.properties");

加載配置文件

屬性占位符#{}
    第一種方式(PropertySourcesPlaceholderConfigurer):
        文件
            src/db.properties(name=root)
        配置
            <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer" p:location="classpath:db.properties"></bean>
            <bean id="user" class="com.shuai.domain.User" p:name="${name}"></bean>
        User.java
            public class User {
                private String name;
                get/set..
            }
        多文件配置
            <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer" p:locations="#{new Object[]{'classpath:db.properties','classpath:log.properties'}}"/>
    第二種方式(配置)
        配置中添加一行 xmlns:context="http://www.springframework.org/schema/context"
            <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.xsd
                    http://www.springframework.org/schema/context
                    http://www.springframework.org/schema/context/spring-context-4.2.xsd"></beans>
        使用標(biāo)簽
            <context:property-placeholder location="classpath:log.properties"/>
            <context:property-placeholder location="classpath:db.properties,classpath:log.properties"/>
屬性重寫
    第一種方式
        文件
            src/db.properties(user.name=root)
        配置
            <bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer" p:location="classpath:db.properties"></bean>
        User.java
            public class User {
                private String name;
                get/set..
            }
        多文件配置
            <bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer" p:locations="#{new Object[]{'classpath:db.properties','classpath:log.properties'}}"></bean>
    第二種方式
        配置中添加一行 xmlns:context="http://www.springframework.org/schema/context"
            <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.xsd
                    http://www.springframework.org/schema/context
                    http://www.springframework.org/schema/context/spring-context-4.2.xsd"></beans>
        使用標(biāo)簽
            <context:property-override location="classpath:db.properties"/>
            <context:property-override location="classpath:db.properties,classpath:log.properties"/>

Spring零配置(注解)

@Component 普通組件
@Controller 控制器組件
@Service 業(yè)務(wù)組件
@Repository 倉儲(chǔ)(數(shù)據(jù)訪問)
@Resource 配置依賴注入
@Autowired/@Qualifier 
@Scope 指定Bean的作用域
@Lazy 延遲初始化
@PostConstruct/@PreDestroy 生命周期
開啟注解掃描
    <context:component-scan base-package=""></context:component-scan>
    掃面所有的 @Component/@Controller/@Service/@Repository 創(chuàng)建實(shí)例交給Spring容器管理

AOP

Spring+struts2

spring4.3.9+struts2.5.13
    1.拷貝Struts2的jar
        struts-2.5.13\apps\struts2-showcase\lib目錄下的所有jar包
        注意:去掉spring的jar包
    2.Web應(yīng)用整合Struts2
        <filter>
            <filter-name>struts-prepare</filter-name>
            <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareFilter</filter-class>
            <init-param>
                <param-name>config</param-name>
                <param-value>struts-default.xml,struts-plugin.xml,struts.xml,struts1.xml</param-value>
            </init-param>
        </filter>
         <filter-mapping>
            <filter-name>struts-prepare</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        <filter>
            <filter-name>struts-execute</filter-name>
            <filter-class>org.apache.struts2.dispatcher.filter.StrutsExecuteFilter</filter-class>
        </filter>
         <filter-mapping>
            <filter-name>struts-execute</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        注意:去掉一些自己不需要的配置
    3.Web應(yīng)用整合Spring4(Spring容器的創(chuàng)建).
        默認(rèn)是WEB-INF目錄/WEB-INF/applicationContext*.xml 或者 applicationContext*.xml(src目錄)
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext*.xml</param-value>
        </context-param>
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    4.Struts2整合Spring4:
        拷貝struts-spring-plugin-xxx.jar 由struts提供,因?yàn)镾pring這個(gè)框架出現(xiàn)的時(shí)間比Struts2晚
        作用:把a(bǔ)ction類的實(shí)例創(chuàng)建交給Spring創(chuàng)建锭吨,創(chuàng)建好后就會(huì)按byName為action實(shí)例中的set方法注入值.注入完成后蠢莺,Spring再把a(bǔ)ction實(shí)例歸還給Struts2.
    5.配置struts配置文件和spring配置文件

spring+hibernate

spring4.3.9+hibernate4.3.11
    1.拷貝hibernate的jar包
        jpa+required+optional/c3p0+mysql-connector-java-5.1.27.jar
    2.創(chuàng)建hibernate.cfg.xml
        <session-factory>
            <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
            <property name="hibfernate.show_sql">true</property>     
            <property name="hibernate.format_sql">true</property>   
            <property name="hibernate.hbm2ddl.auto">update</property>
            <mapping class="com.shuai.domain.User"/>
        </session-factory>
    3.創(chuàng)建src/db.properties
    4.拷貝Springjar包
        20個(gè) + commons-logging-xx.jar + aop依賴的aspectjweaver.jar
    5.創(chuàng)建Spring的配置文件applicationContext.xml
        <beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:p="http://www.springframework.org/schema/p"
            xmlns:tx="http://www.springframework.org/schema/tx"
            xmlns:aop="http://www.springframework.org/schema/aop"
            xmlns:context="http://www.springframework.org/schema/context"
            xsi:schemaLocation="
                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-4.1.xsd
                http://www.springframework.org/schema/tx
                http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context-3.0.xsd"
                default-autowire="byName"></beans>
    6.配置applicationContext.xml
        6.0注意:一定在beans加一個(gè)屬性 default-autowire="byName"
        6.1加載db.properties
            <context:property-placeholder location="classpath:db.properties"/>
        6.2創(chuàng)建數(shù)據(jù)庫連接池
            <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
                p:driverClass="${driverClass}"
                p:jdbcUrl="${jdbcUrl}"
                p:user="${user}"
                p:password="${password}"
                p:maxPoolSize="${maxPoolSize}"
                p:minPoolSize="${minPoolSize}"
                p:initialPoolSize="${initialPoolSize}"/>
        6.3創(chuàng)建數(shù)據(jù)庫數(shù)據(jù)源
            <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
                p:dataSource-ref="dataSource"
                p:configLocation="classpath:hibernate.cfg.xml"/>
        6.4配置aop切面
            <!-- 事務(wù)管理器-->
            <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
                p:sessionFactory-ref="sessionFactory"/> 
            <!-- 配置事務(wù)切面bean(聲明式事務(wù)配置) -->
            <tx:advice id="txAdvice" transaction-manager="transactionManager">
                <tx:attributes>
                    <tx:method name="set*" read-only="true"/>
                    <tx:method name="get*" read-only="true"/>
                    <tx:method name="*" read-only="false"/>
                </tx:attributes>
            </tx:advice>
            <!-- 事務(wù)切面(運(yùn)用到哪些切入點(diǎn)) -->
            <aop:config>
                <aop:pointcut expression="execution(* com.shuai.service.*.*(..))" id="pointcut"/>
                <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
            </aop:config>
    7.代碼
        HibernateDao.java
            public interface HibernateDao {
                <T> void save(T entity);
                <T> void update(T entity);
                <T> T get(Class<?> clazz, Serializable id);
                <T> void delete(T entity);
                <T> List<T> find(String hql);
            }
        HibernateDaoImpl.java
            public class HibernateDaoImpl extends HibernateDaoSupport implements HibernateDao {
                @Override
                public <T> void save(T entity) {
                    this.getHibernateTemplate().save(entity);
                }
                @Override
                public <T> void update(T entity) {
                    this.getHibernateTemplate().update(entity);
                }
                @Override
                public <T> T get(Class<?> clazz, Serializable id) {
                    return (T)this.getHibernateTemplate().get(clazz, id);
                }
                @Override
                public <T> void delete(T entity) {
                    this.getHibernateTemplate().delete(entity);
                }
                @Override
                public <T> List<T> find(String hql) {
                    return (List<T>)this.getHibernateTemplate().find(hql);
                }
            }
        

spring+mybatis

spring4.3.9+mybatis3.4.4
    1.拷貝mybatis3的jar包
        mybatis-3.4.4.jar+mybatis-spring-1.3.1.jar+mysql-connector-java-5.1.27.jar+c3p0-0.9.5.2.jar+mchange-commons-java-0.2.11.jar
    2.編寫src/db.properties
    3.編寫src/mybatis-config.xml
        <?xml version="1.0" encoding="UTF-8" ?>
        <!DOCTYPE configuration
          PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
          "http://mybatis.org/dtd/mybatis-3-config.dtd">
        <configuration>
            <typeAliases>
                <typeAlias type="com.shuai.domain.User" alias="User" />
            </typeAliases>
        </configuration>
    4.拷貝spring的jar包
        20個(gè)+common-logging-xx.jar
    5.配置applicationContext.xml
        5.1注意:beans中不能配置 default-autowire="byName"
        5.2加載數(shù)據(jù)庫配置文件
            <context:property-placeholder location="classpath:db.properties"/>
        5.3創(chuàng)建數(shù)據(jù)源
            <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
                p:driverClass="${driverClass}"
                p:jdbcUrl="${jdbcUrl}"
                p:user="${user}"
                p:password="${password}"
                p:maxPoolSize="${maxPoolSize}"
                p:minPoolSize="${minPoolSize}"
                p:initialPoolSize="${initialPoolSize}"/>
        5.4創(chuàng)建session工廠
            <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
                p:dataSource-ref="dataSource" p:configLocation="classpath:mybatis-config.xml" p:mapperLocations="classpath:com/shuai/domain/*.xml"/>
        5.5加載mybatis配置文件
            <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
                p:basePackage="com.shuai.dao" p:sqlSessionFactoryBeanName="sqlSessionFactory"/>
        5.6配置事務(wù)
            <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
                p:dataSource-ref="dataSource"/>
            <tx:advice id="txAdvice">
                <tx:attributes>
                    <tx:method name="set*" read-only="true"/>
                    <tx:method name="get*" read-only="true"/>
                    <tx:method name="*" read-only="false"/>
                </tx:attributes>
            </tx:advice>
            <aop:config>
                <aop:pointcut expression="execution(* com.shuai.service.*.*(..))" id="pointcut"/>
                <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
            </aop:config>
    6.代碼
        UserDao.java
            public interface UserDao {
                void insert(User user);
            }
        User.xml
            <mapper namespace="com.shuai.dao.UserDao">
                <insert id="insert" parameterType="User">
                    insert into user (name) values (#{name})
                </insert>
            </mapper>

springmvc+spring

spring+log4j

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市零如,隨后出現(xiàn)的幾起案子躏将,更是在濱河造成了極大的恐慌,老刑警劉巖考蕾,帶你破解...
    沈念sama閱讀 216,591評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件祸憋,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡辕翰,警方通過查閱死者的電腦和手機(jī)夺衍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來喜命,“玉大人沟沙,你說我怎么就攤上這事”陂牛” “怎么了矛紫?”我有些...
    開封第一講書人閱讀 162,823評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)牌里。 經(jīng)常有香客問我颊咬,道長(zhǎng)务甥,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,204評(píng)論 1 292
  • 正文 為了忘掉前任喳篇,我火速辦了婚禮敞临,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘麸澜。我一直安慰自己挺尿,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,228評(píng)論 6 388
  • 文/花漫 我一把揭開白布炊邦。 她就那樣靜靜地躺著编矾,像睡著了一般。 火紅的嫁衣襯著肌膚如雪馁害。 梳的紋絲不亂的頭發(fā)上窄俏,一...
    開封第一講書人閱讀 51,190評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音碘菜,去河邊找鬼凹蜈。 笑死,一個(gè)胖子當(dāng)著我的面吹牛炉媒,可吹牛的內(nèi)容都是我干的踪区。 我是一名探鬼主播,決...
    沈念sama閱讀 40,078評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼吊骤,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了静尼?” 一聲冷哼從身側(cè)響起白粉,我...
    開封第一講書人閱讀 38,923評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎鼠渺,沒想到半個(gè)月后鸭巴,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,334評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡拦盹,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,550評(píng)論 2 333
  • 正文 我和宋清朗相戀三年鹃祖,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片普舆。...
    茶點(diǎn)故事閱讀 39,727評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡恬口,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出沼侣,到底是詐尸還是另有隱情祖能,我是刑警寧澤,帶...
    沈念sama閱讀 35,428評(píng)論 5 343
  • 正文 年R本政府宣布蛾洛,位于F島的核電站养铸,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜钞螟,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,022評(píng)論 3 326
  • 文/蒙蒙 一兔甘、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧鳞滨,春花似錦洞焙、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至提岔,卻和暖如春仙蛉,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背碱蒙。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工荠瘪, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人赛惩。 一個(gè)月前我還...
    沈念sama閱讀 47,734評(píng)論 2 368
  • 正文 我出身青樓哀墓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親喷兼。 傳聞我的和親對(duì)象是個(gè)殘疾皇子篮绰,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,619評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容