spring入门及特性

1. spring前的代码

1.1 强耦合调用

Computer和Windows98强耦合调用

package com.zqq.demo1;

/**
 * 电脑
 */
public class Computer {

    /**
     * 操作系统
     */
    Windows98 windows98;

    public Computer(Windows98 windows98) {
        this.windows98 = windows98;
    }

    /**
     * 工作
     */
    public void work(){
        this.windows98.run();
    }
}
package com.zqq.demo1;

/**
 * 操作系统
 */
public class Windows98 {
    /**
     * 运行
     */
    public void run(){
        System.out.println("工作在Windows98上");
    }
}
package com.zqq.demo1;

public class Demo1 {
    /**
     * 运行电脑
     * @param args
     */
    public static void main(String[] args) {
        Computer computer = new Computer(new Windows98());
        computer.work();
    }
}

1.2 接口编程解耦合

Windows98实现ComputerSystem接口

package com.zqq.demo2;

/**
 * 电脑
 */
public class Computer {
    /**
     * 操作系统
     */
    ComputerSystem computerSystem;

    public Computer(ComputerSystem computerSystem) {
        this.computerSystem = computerSystem;
    }

    /**
     * 工作
     */
    public void work(){
        computerSystem.run();
    }
}
package com.zqq.demo2;

/**
 * 操作系统
 */
public interface ComputerSystem {
    /**
     * 运行
     */
    void run();
}

package com.zqq.demo2;

/**
 * 操作系统
 */
public class Windows7 implements ComputerSystem{

    public void run() {
        System.out.println("工作在Windows7上");
    }
}

package com.zqq.demo2;

/**
 * 操作系统
 */
public class Windows98 implements ComputerSystem {
    /**
     * 运行
     */
    public void run() {
        System.out.println("工作在Windows98上");
    }
}

package com.zqq.demo2;

/**
 * 操作系统
 */
public class Windows7 implements ComputerSystem{
    /**
     * 运行
     */
    public void run() {
        System.out.println("工作在Windows7上");
    }
}

package com.zqq.demo2;

public class Demo2 {
    /**
     * 运行电脑
     * @param args
     */
    public static void main(String[] args) {
        ComputerSystem computerSystem = new Windows98();
        Computer computer = new Computer(computerSystem);
        computer.work();
    }
}

1.3 spring IOC 松耦合

在spring中配置可以完成如上main方法中的computerSystem和computer的对象的创建的配置

maven项目添加spring依赖

pom.xml

 <dependencies>
        <!--添加Spring依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    </dependencies>

applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--操作系统-->
    <bean id="window7" class="com.zqq.demo3.Window7"/>
    <bean id="windows98" class="com.zqq.demo3.Windows98"/>
    <!--电脑-->
    <bean id="computer" class="com.zqq.demo3.Computer">
        <constructor-arg ref="window7"></constructor-arg>
    </bean>

</beans>
package com.zqq.demo3;

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

/**
 * Spring配置测试
 */
public class Demo3 {
    /**
     * 电脑运行
     * @param args
     */
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Computer computer = (Computer) context.getBean("computer");
        computer.work();//工作在Windows7系统上
    }

}

2. spring可以做什么?

Spring致力于全方位的简化JAVA开发,为降低开发成本、复杂性,采取以下四种策略:

  • 基于POJO的轻量级和最小侵入性编程;
  • 通过依赖注入和面向切面接口实现松耦合;
  • 基于切面和惯例进行声明式编程;
  • 通过切面和模板减少样板式代码;

2.1 Spring装配Bean

Spring装配Bean对象的三种方式:

  • XML配置
  • 自动化装配(注解)
  • Java代码装配(@Configuation)

2.1.1 XML配置

见1.3

2.1.2 自动化装配(注解)

package com.zqq.demo4;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * 电脑
 */
@Component
public class Computer {

    /**
     * 操作系统
     */
    @Qualifier("windows7")
    @Autowired
    private ComputerSystem computerSystem;

    /**
     * 工作
     */
    public void work(){
        computerSystem.run();
    }
}
package com.zqq.demo4;

/**
 * 操作系统
 */
public interface ComputerSystem {
    /**
     * 运行
     */
    public void run();
}
package com.zqq.demo4;

import org.springframework.stereotype.Component;

/**
 * 操作系统
 */
@Component
public class Windows7 implements ComputerSystem {
    /**
     * 运行
     */
    public void run() {
        System.out.println("运行在Windows7上");
    }
}
package com.zqq.demo4;

import org.springframework.stereotype.Component;

/**
 * 操作系统
 */
@Component
public class Windows98 implements ComputerSystem {
    /**
     * 运行
     */
    public void run() {
        System.out.println("运行在Windows98上");
    }
}
package com.zqq.demo4;

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

/**
 * Spring注解测试
 */
public class Demo4 {

    /**
     * 电脑运行
     * @param args
     */
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext2.xml");
        Computer computer = (Computer) context.getBean("computer");
        computer.work();//运行在Windows7上
    }
}

2.1.3

package com.zqq.demo5;

/**
 * 电脑
 */
public class Computer {
    /**
     * 操作系统
     */
    ComputerSystem computerSystem;

    public Computer(ComputerSystem computerSystem) {
        this.computerSystem = computerSystem;
    }

    /**
     * 工作
     */
    public void work(){
        computerSystem.run();
    }
}
package com.zqq.demo5;

/**
 * 操作系统
 */
public interface ComputerSystem {
    /**
     * 运行
     */
    void run();
}
package com.zqq.demo5;

/**
 * 操作系统
 */
public class Windows7 implements ComputerSystem {
    /**
     * 运行
     */
    public void run() {
        System.out.println("运行在Windows7上");
    }
}
package com.zqq.demo5;

/**
 * 操作系统
 */
public class Windows98 implements ComputerSystem{
    /**
     * 运行
     */
    public void run() {
        System.out.println("运行在Windows98上");
    }
}
package com.zqq.demo5;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Java代码配置
 */
@Configuration
public class SystemConfig {

    @Bean
    public ComputerSystem computerSystem(){
        return new Windows7();
    }

    @Bean
    public Computer computer(){
        return new Computer(computerSystem());
    }

}
package com.zqq.demo5;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Spring Java代码装配
 */
public class Demo5 {
    /**
     * 电脑工作
     * @param args
     */
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(SystemConfig.class);
        Computer computer = (Computer) context.getBean("computer");
        computer.work();
    }
}

2.2 Spring注解

  • @Controller:控制器;
  • @Autowired:自动装配成员变量,@Autowired(required=false) 在找不到匹配Bean时也不报错;
  • @Qualifier:注释指定注入bean的名称,防止冲突。
  • @Component:定义一个bean;
  • @Service:定义一个service bean;
  • @Scope:设置bean的类型;
  • @Repository:定义一个bean,可将该对象中抛出的数据访问异常封装为Spring的数据访问异常。

2.3 Spring依赖注入

@Autowired
以下均可使用

  • 成员变量注入
  • 构造方法注入
  • 设值方法注入

xml配置
同上

2.4 Bean的作用域 Scope

这个链接写得很详细
https://www.jianshu.com/p/fcdcbaace675

  • singleton(单例):在整个应用中,只创建bean的一个实例;
value=ConfigurableBeanFactory.SCOPE_SINGLETON
  • prototype(原型):每次注入或者通过Spring上下文获取时,都会创建一个新的bean实例;
value=ConfigurableBeanFactory.SCOPE_PROTOTYPE
  • session(会话):在web应用中,为每一个会话创建一个bean实例;
value=WebApplicationContext.SCOPE_SESSION
  • request(请求):在web应用中,为每一个请求创建一个bean实例。
value=WebApplicationContext.SCOPE_REQUEST

备注:当bean的作用域设置为session或request时,需要配置proxyMode的值为:interfaces。

2.5 AOP

相关术语

  • 通知(Advice)
    通知定义了切面是什么及何时使用。除了描述切面要完成的工作(日志记录),通知还决定了何时执行。
  1. 前置通知(Befor):目标方法调用前调用通知;
  2. 后置通知(After):目标方法调用后调用通知;
  3. 返回通知(After-returning):目标方法返回成功后调用通知;
  4. 异常通知(After-throwing):目标方法抛出异常后调用通知;
  5. 环绕通知(Around):目标方法调用前与调用后都会调用通知;
  • 连接点(Join point)
    连接点是指在应用执行过程中能够插入切面的一个点(调用方法时)。
  • 切点(Poincut)
    切点定义了何处使用通知。定义匹配通知所要织入的一个或多个连接点。通常使用明确的类和方法名,或是利用正则表达式匹配。
  • 切面(Aspect)
    切面就是通知和切点的结合。
    织入(Weaving)
    把切面应用到目标对象,并创建新的代理对象的过程。
  • 织入

3种实现方式

  • 基于代理的经典Spring AOP;
  • 纯POJO切面;
  • @AspectJ注解驱动切面;

2.5.1 基于代理的经典Spring AOP

package com.zqq.demo6;

import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 切点方法前执行
 */
@Component
public class AopBefore implements MethodBeforeAdvice {
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println("Before the system work ,do something");
    }
}
package com.zqq.demo6;

import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 切点方法前执行
 */
@Component
public class AopBefore implements MethodBeforeAdvice {
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println("Before the system work ,do something");
    }
}

package com.zqq.demo6;

import org.springframework.aop.AfterReturningAdvice;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 切点方法后执行
 */
@Component
public class AopAfter implements AfterReturningAdvice {
    
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("after the system,do something");
    }
}
package com.zqq.demo6;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * 电脑
 */
@Component
public class Computer {

    /**
     * 操作系统
     */
    @Qualifier("systemProxy")
    @Autowired
    private ComputerSystem computerSystem;

    /**
     * 工作
     */
    public void work(){
        computerSystem.run();
    }


}
package com.zqq.demo6;

/**
 * 操作系统
 */
public interface ComputerSystem {
    /**
     * 运行
     */
    void run();
}
package com.zqq.demo6;

import org.springframework.stereotype.Component;

/**
 * 操作系统
 */
@Component
public class Windows7 implements ComputerSystem {
    /**
     * 运行
     */
    public void run() {
        System.out.println("运行在Windows7上");
    }
}
<?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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.zqq.demo6"/>

    <bean id="systemProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="interfaces">
        <value>com.zqq.demo6.ComputerSystem</value>
        </property>
        <property name="target" ref="windows7"/>
        <property name="interceptorNames" >
            <list>
                <value>aopBefore</value>
                <value>aopAfter</value>
            </list>
        </property>
    </bean>

</beans>
package com.zqq.demo6;

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

/**
 * Spring注解测试
 */
public class Demo6 {

    /**
     * 电脑运行
     * @param args
     */
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext6.xml");
        Computer computer = (Computer) context.getBean("computer");
        computer.work();
    }
}

2.5.3

package com.zqq.demo7;

import org.springframework.stereotype.Component;

/**
 * AOP
 */
@Component
public class AopDemo {
    /**
     * 方法前执行
     */
    public void before(){
        System.out.println("before method");
    }
    /**
     * 方法后执行
     */
    public void after(){
        System.out.println("after method");
    }

}
<aop:config>
    <aop:aspect ref="aopDemo">
         <aop:pointcut id="computerPoint" expression="execution(void com.zqq.demo7.Computer.work(..))"/>
         <aop:before method="before" pointcut-ref="computerPoint"/>
         <aop:after method="after" pointcut-ref="computerPoint"/>
        </aop:aspect>
    </aop:config>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 161,326评论 4 369
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,228评论 1 304
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,979评论 0 252
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,489评论 0 217
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,894评论 3 294
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,900评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,075评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,803评论 0 205
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,565评论 1 249
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,778评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,255评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,582评论 3 261
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,254评论 3 241
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,151评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,952评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,035评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,839评论 2 277

推荐阅读更多精彩内容