Spring概述

2017-09-29  本文已影响31人  垃圾简书_吃枣药丸

什么是Spring
Spring是一个容器,管理着整个应用程序中所有的bean的生命周期和依赖关系,从而降低耦合度,具体分为下面两种情况。

spring的出现就是为了解耦合,充当一个管家的角色。
Spring把代码根据功能划分:

  1. 主业务逻辑代码
    1. 代码逻辑联系紧密,耦合度高,复用性低。
    2. 降低主业务代码之间的耦合度 =>> 控制反转 IOC
  2. 系统级业务逻辑(交叉业务逻辑)
    1. 功能相对独立,没有具体的业务场景,主要是提供系统级服务,如日志,安全,事务等,复用性很强。
    2. 降低主业务逻辑和系统级服务之间的耦合度 =>> 面向切面编程 AOP
Spring体系结构

一,控制反转 IOC Inversion of Control

是一种思想,一个概念
IOC实现的两种方式
1. 依赖注入 DI Dependency Injection
2. 依赖查找 DL Dependency Lookup

创建第一个Spring项目

新建Maven工程
POM文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.bjxl</groupId>
    <artifactId>spring4</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <kotlin.version>1.1.51</kotlin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>
        <!--单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--日志-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--相当于slf4j-->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-stdlib-jre8</artifactId>
            <version>${kotlin.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-test</artifactId>
            <version>${kotlin.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.jetbrains.kotlin</groupId>
                <artifactId>kotlin-maven-plugin</artifactId>
                <version>${kotlin.version}</version>
                <executions>
                    <execution>
                        <id>compile</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                        <configuration>
                            <sourceDirs>
                                <source>src/main/java</source>
                                <source>src/main/interface</source>
                            </sourceDirs>
                        </configuration>
                    </execution>
                    <execution>
                        <id>test-compile</id>
                        <phase>test-compile</phase>
                        <goals>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <jvmTarget>1.8</jvmTarget>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

ServiceImpl

package impl

import face.ISomeService

/**
 * Created by futao on 2017/9/29.
 */
class ISomeServiceImpl : ISomeService {
    override fun doFirst(): String {
        println("执行doFirst()方法")
        return "abcde"
    }

    override fun doSecond() {
        println("执行doSecond()方法")
    }

}

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容器-->
    <!--对象容器-->
    <!--注册Service对象,等于Java代码中 ISomeServiceImpl iss = new ISomeServiceImpl()
        这个对象是在Spring容器被初始化的时候Spring自动创建的
    -->
    <bean id="iss" class="impl.ISomeServiceImpl"/>
</beans>

测试

package ServiceTest

import impl.ISomeServiceImpl
import org.junit.Test
import org.springframework.context.ApplicationContext
import org.springframework.context.support.ClassPathXmlApplicationContext

/**
 * Created by futao on 2017/9/29.
 */
class myTest {
    /**
     * 传统方式 new对象
     */
    @Test
    fun test() {
        val iSomeServiceImpl = ISomeServiceImpl()
        iSomeServiceImpl.doFirst()
        iSomeServiceImpl.doSecond()
    }

     /**
     * 从bean容器里面获取
     */
    @Test
    fun test02() {
        //加载Spring配置文件,创建Spring对象,这个时候对象就已经全部被加载到Spring容器当中了
//        val container = ClassPathXmlApplicationContext("applicationContext.xml")
        val container = FileSystemXmlApplicationContext("D:\\eclipse-workspace\\spring4\\src\\main\\resources\\applicationContext.xml")
        //从容器中获取指定Bean对象
        val iss = container.getBean("iss") as ISomeServiceImpl
        iss.doSecond()
        iss.doFirst()
    }
}
}

bean的装配

动态工厂bean

package Factory

import impl.ISomeServiceImpl

/**
 * Created by futao on 2017/9/29.
 */
class dynamicFactory {
    fun getSomeService(): ISomeServiceImpl {
        return ISomeServiceImpl()
    }
}
<?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容器-->
    <!--对象容器-->
    <!--注册Service对象,等于Java代码中 ISomeServiceImpl iss = new ISomeServiceImpl()
        这个对象是在Spring容器被初始化的时候Spring自动创建的
    -->
    <!--<bean id="iss" class="impl.ISomeServiceImpl"/>-->
    <bean id="issFactory" class="Factory.dynamicFactory"/>
    <bean id="iss" factory-bean="issFactory" factory-method="getSomeService"/>
</beans>

静态工厂bean
....

容器中Bean的作用域

scope="prototype" 原型模式,每次都会创建一个新的对象(真正使用的时候才会被创建,每获取一次,都会创建一个新的不同的对象)
scope="singleton" 单例模式,对象只会被创建一次(容器初始化的时候就会进行创建,也就是xml文件加载的时候)(默认的)

Bean后处理器

实现BeanPostProcessor 接口
重写方法postProcessAfterInitialization()和postProcessAfterInitialization()

package beanHandler

import org.springframework.beans.factory.config.BeanPostProcessor

/**
 * Created by futao on 2017/9/29.
 */
class myBeanPostPrecess : BeanPostProcessor {
    //p0 当前调用执行'Bean后处理器'的Bean对象
    //p1 当前调用执行'Bean后处理器'的bean对象的id
    override fun postProcessBeforeInitialization(p0: Any?, p1: String?): Any {
        println("执行了${p0!!::class.java.simpleName},$p1,Before")
        return p0
    }

    override fun postProcessAfterInitialization(p0: Any?, p1: String?): Any {
        println("执行了${p0!!::class.java.simpleName},$p1,After")
        return p0
    }
}

测试

@Test
    fun test03() {
        val iss = ClassPathXmlApplicationContext("applicationContext.xml")
        val service = iss.getBean("iss") as ISomeServiceImpl
        service.doFirst()
        service.doSecond()


        println("================")

        val s2=iss.getBean("dyb") as ISomeServiceImpl
        s2.doSecond()
        s2.doFirst()
    }

结果

Result

Bean的生命周期

package impl

import face.ISomeService

/**
 * Created by futao on 2017/9/29.
 */
class ISomeServiceImpl : ISomeService {
    override fun doFirst(): String {
        println("执行doFirst()方法")
        return "abcde"
    }

    override fun doSecond() {
        println("执行doSecond()方法")
    }

    fun initAtfer() {
        println("初始化之后")
    }

    fun beforeDestory() {
        println("销毁之前")
    }

}

XML

 <bean id="iss" class="impl.ISomeServiceImpl" init-method="initAtfer" destroy-method="beforeDestory"/>

Test

  @Test
    fun test03() {
    
        val iss = ClassPathXmlApplicationContext("applicationContext.xml")
        val service = iss.getBean("iss") as ISomeServiceImpl
        println(service.doFirst())
        service.doSecond()
        println("================")
        val s2=iss.getBean("dyb") as ISomeServiceImpl
        s2.doSecond()
        s2.doFirst()
    //销毁方法的执行需要两个要求
        /*
        *   1)被销毁的对象需要是singleton的
        *   2)容器要显式地关闭
        * */
        iss.destroy()
    }
上一篇下一篇

猜你喜欢

热点阅读