spring学习笔记

阅读书籍《spring in action》第三版(Walls,c.)

这本书理解起来比较难,所以只关注了依赖注入(DI)和面向切面编程(aop)

1.DI

spring的三种注入方式:

  • 构造器注入
  • setter方法注入
  • 工厂方法注入
 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-3.1.xsd">
 6     
 7     <bean id="duke" class="com.dreamich.springdemo.ioc.impl.BeanDemo1">
 8         <constructor-arg value = "15"/><!-- 构造器注入 -->
 9     </bean>
10     
11     <bean id="dukeChild" class="com.dreamich.springdemo.ioc.impl.BeanDemoChild" factory-method="factoryMethord"> <!--factory-method 工厂方法注入 -->
12         <!-- <constructor-arg value = "15"/> --><!-- 构造器注入 -->
13         <!-- <constructor-arg ref = "other"/> --><!-- 构造器注入,ref表示对象引用,注入id为“other”的bean -->
14         <!-- <property name="i" value = "8"/> --><!-- setter方法注入 -->
15         <!-- <property name="beanDemoOther" ref = "other"/> -->
16     </bean>
17     
18     <bean id="other" class="com.dreamich.springdemo.ioc.impl.BeanDemoOther1">
19         <constructor-arg value = "6"/><!-- 构造器注入 -->
20         
21     </bean>
22     
23 
24 </beans>
View Code

 使用命名空间p装配属性

<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"
    >
    <!-- xmlns:p   配置后可以使用命名空间p -->
    
    <bean id="duke" class="com.dreamich.springdemo.ioc.impl.BeanDemo1"/>
    
    <bean id="dukeChild" class="com.dreamich.springdemo.ioc.impl.BeanDemoChild"  p:i="10" p:beanDemoOther-ref="other"/>
    <!-- -ref后缀作为一个标志,表示此处为引用而不是字面值 -->
    
    <bean id="other" class="com.dreamich.springdemo.ioc.impl.BeanDemoOther1">
        <constructor-arg value = "6"/><!-- 构造器注入 -->
        
    </bean>
</beans>
View Code

装配集合:spring集合配置元素

  • <list>  装配list类型的值,允许重复
  • <set>  装配set类型的值,不允许重复
  • <map>     装配map类型的值,名称和值可以是任何类型
  • <props>   装配properties类型的值,名称和值必须为字符串
<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"
    >
    <!-- xmlns:p   配置后可以使用命名空间p -->
    
    <bean id="duke" class="com.dreamich.springdemo.ioc.impl.BeanDemo1">
        <property name="xxxxxxxxxx">
            <list>
                <ref bean="xx"/>
                <ref bean="xxx"/>
                <ref bean="xxxx"/>
            </list>
        </property>
        <property name="xxxxxxxxxx">
            <set>
                <ref bean="xx"/>
                <ref bean="xxx"/>
                <ref bean="xxxx"/>
            </set>
        </property>
        <property name="xxxxxxxxxx">
            <map>
                <entry key="xx" value-ref="xx" />
                <entry key="xxx" value-ref="xxx" />
                <entry key="xxxx" value-ref="xxxx" />
            </map>
        </property>
        <property name="xxxxxxxxxx">
            <props>
                <prop key="xx">one</prop>
                <prop key="xxx">two</prop>
                <prop key="xxxx">three</prop>
            </props>
        </property>
    </bean>
    
    <bean id="dukeChild" class="com.dreamich.springdemo.ioc.impl.BeanDemoChild"  p:i="10" p:beanDemoOther-ref="other"/>
    <!-- -ref后缀作为一个标志,表示此处为引用而不是字面值 -->
    
    <bean id="other" class="com.dreamich.springdemo.ioc.impl.BeanDemoOther1">
        <constructor-arg value = "6"/><!-- 构造器注入 -->
        
    </bean>
</beans>
View Code

装配空值:自带默认值不为空,配置的时候设为空值,使用<null/>

<bean id="duke" class="com.dreamich.springdemo.ioc.impl.BeanDemo1">
        <property name="xxxxxxxxxx"><null/></property>
    </bean>
View Code

使用表达式匹配(page54)

2.注解的方式实现依赖注入

  spring文件配置

<?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:p="http://www.springframework.org/schema/p"
    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.1.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd"
    >
    
    <!-- 打开注入 -->
    <context:annotation-config />
    <context:component-scan base-package="com.dreamich.springdemo.ioc.impl"></context:component-scan>
</beans>
View Code

java代码:

package com.dreamich.springdemo.ioc.impl;

import org.springframework.stereotype.Service;

import com.dreamich.springdemo.ioc.interf.BeanDemoOther;

@Service("beanDemoOther")
public class BeanDemoOther1 implements BeanDemoOther{
    int m = 5;
    public BeanDemoOther1() {
    }
    public BeanDemoOther1( int m) {
        this.m = m;
    }
    
    public int getM() {
        return m;
    }
    public void setM(int m) {
        this.m = m;
    }
    @Override
    public void methordOther() {
        System.out.println("methordOther输出"+m+"========================================");
    }
}


package com.dreamich.springdemo.ioc.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dreamich.springdemo.ioc.interf.BeanDemoOther;

@Service("dukeChild")
public class BeanDemoChild extends BeanDemo1{
    
    @Autowired
    private BeanDemoOther beanDemoOther;
    public BeanDemoChild() {
        // TODO Auto-generated constructor stub
    }
    public BeanDemoChild(BeanDemoOther beanDemoOther) {
        super();
        this.beanDemoOther = beanDemoOther;
        // TODO Auto-generated constructor stub
    }
    public BeanDemoChild(int i,BeanDemoOther beanDemoOther) {
        super(i);
        this.beanDemoOther = beanDemoOther;
        // TODO Auto-generated constructor stub
    }
    
    public static BeanDemoChild factoryMethord(){
        BeanDemoOther beanDemoOther = new BeanDemoOther1(10);
        BeanDemoChild demoChild = new BeanDemoChild(beanDemoOther);
        return demoChild;
    }
    
    @Override
    public void demoMethord() throws Exception {
        // TODO Auto-generated method stub
        super.demoMethord();
        System.out.println("+++++++++++++++++++++++++++++++++++++++");
        beanDemoOther.methordOther();
    }
    public BeanDemoOther getBeanDemoOther() {
        return beanDemoOther;
    }
    public void setBeanDemoOther(BeanDemoOther beanDemoOther) {
        this.beanDemoOther = beanDemoOther;
    }
    
}
View Code

<context:component-scan>

@Service  标注该类定义为服务
@Component  标注该类为spring组件
@Repository  标注该类定义为数据仓库
@Controller  标注该类为springMvc控制器

 2.aop面向切面编程

  术语

  • 通知:定义了切面要完成的工作,以及何时执行。(分为5中类型:Before:方法调用之前调用通知;After:方法完成之后调用通知;After-returning:方法成功返回后调用通知;After-throwing:方法抛出异常后调用通知;Around:方法调用之前和之后执行自定义的行为)
  • 连接点:应用执行过程中能够插入通知的一个点
  • 切点:通知要织入的一个或多个连接点
  • 切面:通知和切点的结合
  • 引入:允许我们向现有的类添加新的方法和属性
  • 织入:将切面应用到目标对象来创建新的代理对象的过程

  xml配置

<?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:p="http://www.springframework.org/schema/p"
    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.1.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
    >
    
    <bean id = "audience" class="com.dreamich.springdemo.aop.impl.AudienceImpl"/>
    <bean id = "pointcut" class="com.dreamich.springdemo.aop.impl.PointCutImpl"/>
    <aop:config>
        <aop:aspect ref="audience">
            <!-- <aop:before method="before" pointcut="execution(* com.dreamich.springdemo.aop.impl.PointCutImpl.pointMethord())"/> -->
            <!-- <aop:after method="after" pointcut="execution(* com.dreamich.springdemo.aop.impl.PointCutImpl.pointMethord())"/> -->
            <!-- <aop:after-returning method="afterReturn" pointcut="execution(* com.dreamich.springdemo.aop.impl.PointCutImpl.pointMethord())"/> -->
            <!-- <aop:after-throwing method="afterException" pointcut="execution(* com.dreamich.springdemo.aop.impl.PointCutImpl.pointMethord())"/> -->
            <aop:around method="around" pointcut="execution(* com.dreamich.springdemo.aop.impl.*.*())"/>
        </aop:aspect>
    </aop:config>
</beans>
View Code

  java文件:

package com.dreamich.springdemo.aop.interf;

public interface PointCut {
    void pointMethord() throws Exception;
}
=========================================
package com.dreamich.springdemo.aop.impl;

import com.dreamich.springdemo.aop.interf.PointCut;

public class PointCutImpl implements PointCut{
    @Override
    public void pointMethord() throws Exception{
        System.out.println("for business");
        //throw new Exception("test for aop after-throwing");
    }
}
=========================================
package com.dreamich.springdemo.aop.interf;

import org.aspectj.lang.ProceedingJoinPoint;

public interface Audience {
    void before();
    void after();
    void afterReturn();
    void afterException();
    void around(ProceedingJoinPoint joinPoint);
}
=========================================
package com.dreamich.springdemo.aop.impl;

import org.aspectj.lang.ProceedingJoinPoint;

import com.dreamich.springdemo.aop.interf.Audience;

public class AudienceImpl implements Audience{
    @Override
    public void before() {
        System.out.println("before methord");
    }
    @Override
    public void after() {
        System.out.println("after methord");
    }
    @Override
    public void afterReturn() {
        System.out.println("after methord return");
    }
    @Override
    public void afterException() {
        System.out.println("after methord exception");
    }
    @Override
    public void around(ProceedingJoinPoint joinPoint) {
        try{
            System.out.println("before methord");
            joinPoint.proceed();
            
            System.out.println("after methord");
        }catch(Throwable t){
            t.printStackTrace();
            System.out.println("after methord exception");
        }
    }
}
View Code

  测试类

package com.dreamich.springdemo.ioc.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.dreamich.springdemo.aop.interf.PointCut;

public class Test {
    @SuppressWarnings("resource")
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/spring-beans.xml");
        //BeanDemo dukeChild = (BeanDemo)context.getBean("dukeChild");
        PointCut pointcut = (PointCut)context.getBean("pointcut");
        
        try {
            pointcut.pointMethord();
            //dukeChild.demoMethord();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
View Code

 注入的方式,实现aop

  xml文件添加如下配置,作用是支持@Aspect等的相关注解

  <aop:aspectj-autoproxy/>

  java文件:

package com.dreamich.springdemo.aop.interf;

public interface PointCut {
    void pointMethord() throws Exception;
}
==========================================
package com.dreamich.springdemo.aop.impl;

import org.springframework.stereotype.Service;

import com.dreamich.springdemo.aop.interf.PointCut;

@Service("pointcutService")
public class PointCutImpl implements PointCut{
    @Override
    public void pointMethord() throws Exception{
        System.out.println("for business");
        //throw new Exception("test for aop after-throwing");
    }
}
=========================================
package com.dreamich.springdemo.aop.interf;

import org.aspectj.lang.ProceedingJoinPoint;

public interface Audience {
    /*void before();
    void after();
    void afterReturn();
    void afterException();*/
    void around(ProceedingJoinPoint joinPoint);
}
=========================================
package com.dreamich.springdemo.aop.impl;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Service;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;

import com.dreamich.springdemo.aop.interf.Audience;

@Aspect
@Service("audience")
public class AudienceImpl implements Audience{
    
    @Pointcut("execution(* com.dreamich.springdemo.aop.impl.*.*())")
    public void pointcut(){
        
    }
    /*@Override
    @Before(value = "pointcut()")
    public void before() {
        System.out.println("before methord");
    }
    @Override
    @After(value = "pointcut()")
    public void after() {
        System.out.println("after methord");
    }
    @Override
    @AfterReturning(value = "pointcut()")
    public void afterReturn() {
        System.out.println("after methord return");
    }
    @Override
    @AfterThrowing(value = "pointcut()")
    public void afterException() {
        System.out.println("after methord exception");
    }*/
    @Override
    @Around(value = "pointcut()")
    public void around(ProceedingJoinPoint joinPoint) {
        try{
            System.out.println("before methord");
            joinPoint.proceed();
            
            System.out.println("after methord");
        }catch(Throwable t){
            t.printStackTrace();
            System.out.println("after methord exception");
        }
    }
}
==================test类===================
package com.dreamich.springdemo.ioc.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.dreamich.springdemo.aop.interf.PointCut;

public class Test {
    @SuppressWarnings("resource")
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/spring-beans.xml");
        PointCut pointcut = (PointCut)context.getBean("pointcutService");
        
        try {
            pointcut.pointMethord();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
View Code

 

posted @ 2017-08-07 16:51  dream_ich  阅读(200)  评论(0)    收藏  举报