Spring framework

Table of Contents

1 Spring简介

The Spring Framework is an application framework and inversion of control container (IoC) for the Java platform. It help to decouple your project components' dependencies. It has become popular as an alternative to, replacement for, or even addition to the Enterprise JavaBeans (EJB) model.

Spring有两个核心特性:依赖注入(Dependency Injection,DI)和面向切面编程(Aspect-Oriented Programming,AOP)。DI能够让相互协作的软件组件保持松散耦合,而AOP允许你把遍布应用各处的功能分离出来形成可重用的组件。

参考:
Spring Framework Documentation: https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/index.html
Spring Tutorial: http://www.tutorialspoint.com/spring/index.htm
Spring实现用户管理类的入门例子:http://blog.csdn.net/jnqqls/article/details/8622020

1.1 Spring和工厂模式

有人说:反转控制容器(如Spring框架)是最好的工厂模式。各个类中不需要生成其他类的实例,完全由XML配置文件指定。Spring的反转控制容器为你生成对象,把对象的引用塞给Spring管理的类中。这样,类之间就完全解耦了。但也有人说:虽然Spring美其名曰解藕了,但实际上是把原来工厂模式中的耦合性转移到了XML文件中。

1.2 环境配置

Spring framework依赖于org.apache.commons.logging package,可从这里下载:http://commons.apache.org/proper/commons-logging/
Spring framework的库文件可以从这里下载:http://repo.spring.io/release/org/springframework/spring/

下载上面的库文件后,把所有jar包配置到环境变量CLASSPATH中即可。

参考:http://www.tutorialspoint.com/spring/spring_environment_setup.htm

1.3 Hello World


下面演示利用Spring写一个简单的Hello World程序,消息"Hello World"将从XML文件中获取。

Following is the content of HelloWorld.java:

package com.xyz;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }

   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

Following is the content of MainApp.java:

package com.xyz;

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

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      HelloWorld obj = (HelloWorld) context.getBean("MyFirstBean");
      obj.getMessage();
   }
}

Following is the content of Beans.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-3.0.xsd">

   <bean id="MyFirstBean" class="com.xyz.HelloWorld">
       <property name="message" value="Hello World!"/>
   </bean>

</beans>

编译运行如下:

$ find .
.
./Beans.xml
./com
./com/xyz
./com/xyz/HelloWorld.java
./com/xyz/MainApp.java
$ export CLASSPATH=.:~/Downloads/spring-framework-4.1.0.RELEASE/libs/*:~/Downloads/commons-logging-1.2/commons-logging-1.2.jar
$ javac com/xyz/MainApp.java
$ java com/xyz/MainApp
Nov 14, 2015 9:42:56 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@23ab930d: startup date [Tue Nov 14 21:42:56 CST 2015]; root of context hierarchy
Nov 14, 2015 9:42:56 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
Your Message : Hello World!

参考:http://www.tutorialspoint.com/spring/spring_hello_world_example.htm

2 配置Bean

2.1 实例化Bean的三种方式

2.1.1 通过“属性注入”和“构造注入”创建对象

有2种注入方式可以创建对象:
1、属性注入:通过无参构造函数和setter方法注入;
2、构造注入:通过有参的构造函数注入。

1.3 中的例子就是通过“属性注入”创建对象的例子。

下面介绍如何通过“构造注入”来创建对象。假设你有下面类:

package examples;

public class ExampleBean {

    // Number of years to calculate the Ultimate Answer
    private int years;

    // The Answer to Life, the Universe, and Everything
    private String ultimateAnswer;

    public ExampleBean(int years, String ultimateAnswer) {
        this.years = years;
        this.ultimateAnswer = ultimateAnswer;
    }
}

构造注入形式1:

<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg type="int" value="7500000"/>
    <constructor-arg type="java.lang.String" value="42"/>
</bean>

构造注入形式2:

<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg index="0" value="7500000"/>
    <constructor-arg index="1" value="42"/>
</bean>

构造注入形式3:

<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg name="years" value="7500000"/>
    <constructor-arg name="ultimateAnswer" value="42"/>
</bean>

2.1.2 通过静态方法创建对象

假设你有下面类:

public class ClientService {
    private static ClientService clientService = new ClientService();
    private ClientService() {}

    public static ClientService createInstance() {
        return clientService;
    }
}

指定Bean的 factory-method 属性可以通过静态方法来创建对象,如:

<bean id="clientService"
    class="examples.ClientService"
    factory-method="createInstance"/>

2.1.3 通过工厂类创建对象

假设有下面工厂类:

public class DefaultServiceLocator {

    private static ClientService clientService = new ClientServiceImpl();

    public ClientService createClientServiceInstance() {
        return clientService;
    }
}

指定Bean的 factory-beanfactory-method 属性可以通过工厂类创建对象,如:

<bean id="serviceLocator" class="examples.DefaultServiceLocator">
    <!-- inject any dependencies required by this locator bean -->
</bean>

<bean id="clientService"
    <!-- factory-bean设置为工厂类bean的id  -->
    factory-bean="serviceLocator"
    <!-- factory-bean设置为工厂类中的方法  -->
    factory-method="createClientServiceInstance"/>

2.2 Bean scopes

Spring中Bean的作用域如表 1 所示。

Table 1: Bean Scopes
Scope Description
singleton 在Spring IoC容器中仅存在一个Bean实例。这是默认值,即默认地所有Bean都是单例模式。
prototype 每次调用getBean()时,都返回一个新的实例。
request 每个HTTP请求都会创建一个新的Bean,该作用域仅适用于WebApplicationContext环境。
session 同一个HTTP Session共享一个Bean,不同Session使用不同的Bean,该作用域仅适用于WebApplicationContext环境。
application 在每个ServletContext中仅一个Bean,该作用域仅适用于WebApplicationContext环境。
websocket 每个WebSocket中仅一个Bean,该作用域仅适用于WebApplicationContext环境。

注:Bean的默认scope为singleton,所以定义Bean时 scope="singleton" 可以省略,如下面两个Bean定义是相同的:

<bean id="accountService" class="com.foo.DefaultAccountService"/>
<bean id="accountService" class="com.foo.DefaultAccountService" scope="singleton"/>

参考:https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-factory-scopes

3 AOP

4 Spring MVC

为什么使用Spring MVC呢?简单地说就是让开发者只关心核心业务的开发,框架帮你屏蔽原有技术跟业务开发无关的各类技术问题。

参考:
https://blog.csdn.net/Melod_bc/article/details/53414900
https://blog.csdn.net/xlgen157387/article/details/78884005


Author: cig01

Created: <2015-11-14 Sat 00:00>

Last updated: <2018-09-01 Sat 15:22>

Creator: Emacs 25.3.1 (Org mode 9.1.4)