编程笔记

微服务之 Spring 框架核心

2019-01-05  本文已影响0人  老瓦在霸都

Spring 如雷贯耳, 在 Java Web 开发领域无人不晓, 似乎也没什么可说的, 不过时至今日, Spring 已经不仅仅是一个应用程序框架, 一个控制反转容器, 而是一个开源框架的集合, Spring 也已经是 Java 世界中事实上的标准, J2EE 从标准制定者变为模仿者.

Spring 的第一版是 Rod Johson 在写下面这本书的时候开发出来.

这本书2002 写成, 我2006年的时候来买了一本中文版, 也才正式接触了 Spring , 时间过得真快, 12年过去了, Spring 从1.0 发展到了 5.0 版本, Spring 社区也发展壮大如斯

核心框架变化不小, 子项目也林林总总一大堆. 光是 Spring 框架就需要用一本书或一套书的内容来讲述, 我也不可能在这里讲深讲透, 大家其实多数也都知道, 这里只简单总结一下 Spring 框架的基本理念和核心技术

Spring 的核心其实就是 IoC 和 AOP, 再加上众多的注解, 大大简化了配置, 先来回顾一下 IoC Container 控制反转容器

IoC(Inversion of Control) 也称为依赖注入(Dedency Injection) , 这是一个设置依赖关系的过程,通过这个过程,对象定义它们的依赖关系,即它们使用的其他对象,只能通过构造函数参数,工厂方法的参数,或者在构造或从工厂方法返回后在对象实例上设置的属性。 然后容器在创建bean时注入这些依赖项。因为这个过程是相反的,所以叫做 Inversion of Control(IoC),bean本身通过使用类的直接构造或诸如Service Locator模式之类的机制来控制其依赖关系的实例化或位置。

org.springframework.beans 和 org.springframework.context 包 是Spring Framework的IoC容器的基础。 BeanFactory接口提供了一种能够管理任何类型对象的高级配置机制。 ApplicationContext是BeanFactory的子接口。它增加了与Spring的AOP功能的更容易的集成;消息资源处理(用于国际化),事件发布;和特定于应用程序层的上下文,例如WebApplicationContext,用于Web应用程序。

简而言之,BeanFactory提供配置框架和基本功能,ApplicationContext添加了更多高级功能。 ApplicationContext 是 BeanFactory 的超集.

@startuml

BeanFactory <|-- ListableBeanFactory 
ListableBeanFactory <|-- ApplicationContext 
ApplicationContext <|-- ConfigurableApplicationContext
ApplicationContext <|-- WebApplicationContext
WebApplicationContext <|-- ConfigurableWebApplicationContext
ConfigurableWebApplicationContext <|.. AbstracRefreshableConfigurableWebApplicationContext
ConfigurableApplicationContext <|.. AbstractApplicationContext  
AbstractApplicationContext <|-- GenericApplicationContext  
GenericApplicationContext <|-- AnnotationConfigApplicationContext
AbstracRefreshableConfigurableWebApplicationContext <|-- AnnotationConfigWebApplicationContext

@enduml

传统的基于 XML 配置文件的 ClassPathXmlApplicationContext 已经落伍了, 更加简洁是基于注解的 Java 文件配置方式.

ApplicationContext 也就是Spring 容器管理bean的生命周期,包括对象的创建,销毁等, 所以我们只需从容器直接获取Bean对象就行,而不用编写代码来创建bean对象.

Bean 的生命周期由容器管理, 有如下 Bean Scope

Scope Description
singleton 缺省值, 将 Bean 的范围定义为单例
prototype 将 Bean 的范围定义为原型, 也就是会有多少对象实例
request 将 Bean 的范围定义在 HTTP Request 的生命周期内, 一个 Http 请求有一个 Bean 实例, 这个范围类型只在 web-aware 即 Web 类型的 ApplicationContext 中才有效
session 将 Bean 的范围定义在 HTTP Session 的生命周期内, 只在 web-aware 即 Web 类型的 ApplicationContext 中才有效
application 将 Bean 的范围定义在 ServletContext 的生命周期内, 只在 web-aware 即 Web 类型的 ApplicationContext 中才有效
websocket 将 Bean 的范围定义在 WebSocket 的生命周期内, 只在 web-aware 即 Web 类型的 ApplicationContext 中才有效

而在 Bean 的创建销毁的你都可以注册若干处理器, 例如 BeanPostProcessor, 容器在创建完 Bean 的时候会调用它来完成一个后续工作, 比如依赖项的注入, 构造函数完成之后的一些初始化工作

举例如下:

(使用了lombok 的 @Slf4j @Data 来自动生成 log 和 setter/getter/toString 之类的代码, 参见 https://projectlombok.org/ )

package com.github.walterfan.hellospring;

import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.io.support.ResourcePropertySource;

import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.function.Function;


@Slf4j
public class MainApp
{

    @Autowired
    private FileService fileService;

    public static void main(String[] args) throws IOException
    {
        try(AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {

            ctx.getEnvironment().getPropertySources().addFirst(
                    new ResourcePropertySource("classpath:application.properties"));


            ctx.register(LogBeanPostProcessor.class);
            ctx.register(MainConfig.class);
            ctx.refresh();

            MainApp app = ctx.getBean(MainApp.class);

            Potato p1 = ctx.getBean(Potato.class, "sleep");


            log.info("Potato1: {}" , p1);


            Function<String, Potato> factory = (Function<String, Potato> )ctx.getBean("potatoFactory", "sleep");
            Potato p2 = factory.apply("read");

            log.info("Potato2: {}" , p2);
            log.info("App Id: {}" , ctx.getEnvironment().getProperty("app.id"));

            app.listFiles(".", ".java");
        }


    }

    public void listFiles(String dirName, String fixExt) {
        try {
            System.out.println("-- list files --");
            List<Path> files = fileService.getFiles(dirName, fixExt);
            files.forEach(System.out::println);
        } catch (IOException e) {
            log.error("listFiles error", e);
        }

    }

    @Override
    public String toString() {
        return "MainApp { fileService=" + fileService + '}';
    }
}

package com.github.walterfan.hellospring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import java.time.Instant;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;


@Configuration
@Slf4j
public class MainConfig
{
    private AtomicLong idGeneerator = new AtomicLong(0);

    @Bean
    public Function<String, Potato> potatoFactory() {
        return name -> {
            Potato p = getPotato(name);
            p.setCreateTime(Instant.now());
            return p;
        };
    }

    @Bean
    @Scope("prototype")
    public Potato getPotato(String name)
    {
        Potato p = new Potato();
        p.setId(String.valueOf(idGeneerator.incrementAndGet()));
        p.setName(name);

        return p;
    }

    @Bean
    public MainApp mainApp()
    {
        return new MainApp();
    }

    @Bean
    public FileService fileSerivce()
    {
        return new FileService();
    }
}
package com.github.walterfan.hellospring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import static java.util.stream.Collectors.toList;

@Slf4j
@Service
public class FileService {

    public List<Path> getFiles(String dirName, String fileExt) throws IOException {
        Path filePath = Paths.get(dirName);
        return Files.walk(filePath)
                .filter(s -> s.toString().endsWith(fileExt))
                .map(Path::getFileName)
                .sorted()
                .collect(toList());
    }

    @Override
    public String toString() {
        return "FileService";
    }

    @PostConstruct
    public void setup() {
        log.info("FileService setup");
    }

    @PreDestroy
    public void teardown() {
        log.info("FileService teardown");
    }
}

package com.github.walterfan.hellospring;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.time.Instant;
import java.util.List;

@Data
@Slf4j
public class Potato {
    private String id;

    private String name;

    private int priority;

    private String description;

    private List<String> tags;

    private Instant deadline;

    private Instant createTime;

    @PostConstruct
    public void setup() {
        log.info("Potato setup");
    }

    @PreDestroy
    public void teardown() {
        log.info("Potato teardown");
    }
}

  1. LogBeanPostProcessor
package com.github.walterfan.hellospring;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanPostProcessor;

@Slf4j
public class LogBeanPostProcessor implements BeanPostProcessor {
    
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        log.info("Bean '" + beanName + "' postProcessBeforeInitialization ");
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) {
        log.info("Bean '" + beanName + "' postProcessAfterInitialization : " + bean.toString());
        return bean;
    }
}

运行结果如下

08:31:53.126  INFO  o.s.c.a.AnnotationConfigApplicationContext Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@735b5592: startup date [Sun Aug 12 08:31:53 CST 2018]; root of context hierarchy
08:31:53.451  INFO  c.g.w.h.LogBeanPostProcessor Bean 'org.springframework.context.event.internalEventListenerProcessor' postProcessBeforeInitialization 
08:31:53.451  INFO  c.g.w.h.LogBeanPostProcessor Bean 'org.springframework.context.event.internalEventListenerProcessor' postProcessAfterInitialization : org.springframework.context.event.EventListenerMethodProcessor@7a69b07
08:31:53.455  INFO  c.g.w.h.LogBeanPostProcessor Bean 'org.springframework.context.event.internalEventListenerFactory' postProcessBeforeInitialization 
08:31:53.455  INFO  c.g.w.h.LogBeanPostProcessor Bean 'org.springframework.context.event.internalEventListenerFactory' postProcessAfterInitialization : org.springframework.context.event.DefaultEventListenerFactory@3f197a46
08:31:53.460  INFO  c.g.w.h.LogBeanPostProcessor Bean 'mainConfig' postProcessBeforeInitialization 
08:31:53.460  INFO  c.g.w.h.LogBeanPostProcessor Bean 'mainConfig' postProcessAfterInitialization : com.github.walterfan.hellospring.MainConfig$$EnhancerBySpringCGLIB$$4df33095@6ca8564a
08:31:53.589  INFO  c.g.w.h.LogBeanPostProcessor Bean 'potatoFactory' postProcessBeforeInitialization 
08:31:53.589  INFO  c.g.w.h.LogBeanPostProcessor Bean 'potatoFactory' postProcessAfterInitialization : com.github.walterfan.hellospring.MainConfig$$Lambda$1/934275857@5c5eefef
08:31:53.607  INFO  c.g.w.h.LogBeanPostProcessor Bean 'fileSerivce' postProcessBeforeInitialization 
08:31:53.607  INFO  c.g.w.hellospring.FileService FileService setup
08:31:53.607  INFO  c.g.w.h.LogBeanPostProcessor Bean 'fileSerivce' postProcessAfterInitialization : FileService
08:31:53.608  INFO  c.g.w.h.LogBeanPostProcessor Bean 'mainApp' postProcessBeforeInitialization 
08:31:53.609  INFO  c.g.w.h.LogBeanPostProcessor Bean 'mainApp' postProcessAfterInitialization : MainApp { fileService=FileService}
08:31:53.656  INFO  c.g.w.h.LogBeanPostProcessor Bean 'getPotato' postProcessBeforeInitialization 
08:31:53.656  INFO  c.g.walterfan.hellospring.Potato Potato setup
08:31:53.656  INFO  c.g.w.h.LogBeanPostProcessor Bean 'getPotato' postProcessAfterInitialization : Potato(id=1, name=sleep, priority=0, description=null, tags=null, deadline=null, createTime=null)
08:31:53.657  INFO  c.g.walterfan.hellospring.MainApp Potato1: Potato(id=1, name=sleep, priority=0, description=null, tags=null, deadline=null, createTime=null)
08:31:53.660  INFO  c.g.w.h.LogBeanPostProcessor Bean 'getPotato' postProcessBeforeInitialization 
08:31:53.660  INFO  c.g.walterfan.hellospring.Potato Potato setup
08:31:53.661  INFO  c.g.w.h.LogBeanPostProcessor Bean 'getPotato' postProcessAfterInitialization : Potato(id=2, name=read, priority=0, description=null, tags=null, deadline=null, createTime=null)
08:31:53.662  INFO  c.g.walterfan.hellospring.MainApp Potato2: Potato(id=2, name=read, priority=0, description=null, tags=null, deadline=null, createTime=2018-08-12T00:31:53.662Z)
08:31:53.689  INFO  c.g.walterfan.hellospring.MainApp App Id: hellospring
-- list files --
FileService.java
MainApp.java
MainConfig.java
Potato.java

如上所示, MainApp, MainConfig, FileService 是单例, 只会有一个, 在容器创建时创建, 容器销毁时销毁,
而类 Potato 的 scope 是原型, 容器会创建了多个实例, 每个实例创建完后就会调用 LogBeanPostProcessor 的 postProcessBeforeInitialization 方法, Bean被 @PostConstruct 修饰过的postProcessAfterInitialization 方法

参考资料

上一篇下一篇

猜你喜欢

热点阅读