Spring In Action 学习笔记:入门

本文介绍Spring框架的基础概念,包括依赖注入、面向切面编程及如何使用Spring管理组件间的依赖关系。探讨了Spring的配置方式,从XML到Java配置,并演示了如何通过切面增强对象行为。

spring入门基础

以下文字和代码基本摘自Spring in action 第四版


  • 一个Spring组件可以是任何形式的POJO

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

依赖注入(Dependency Injection DI)

依赖可理解为与自身对象相互协作的对象,如在自身属性中有对其他对象的引用以及直接的实例化而非参数传递



public class Knight{

    private Quest quest;

    public Knight(){

        this.quest = new Quest();//紧耦合

    }

    public void embarkOnQUest(){

        quest.embark();

    }

}

通过DI,对象的依赖关系将由系统中负责协调各对象的第三方组件在创建对象的时候进行设定,
即将所依赖的关系自动交给目标对象,而不是让对象自己去获取依赖

public class Knight{    
    private Quest quest;

    public Knight(Quest quest){

        this.quest = quest;//被注入

    }

    public void embarkOnQUest(){

        quest.embark();

    }

}


创建应用组件之间协作的行为通常称为装配(wiring),可通过xml和Java代码配置

Java代码配置需要@Configuration注解

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="****"  ****>
    <bean id="knight" class="包名.类名">
        <constructor-arg ref="quest"/>  //注入构造器参数
    </bean>

    <bean id="quest" class="">
        ***
    </bean>

等价于

@Configuration
public class KnightConfig{

    @Bean
    public Knight knight(){

        return new Knight(quest());
    }

    @Bean
    public Quest quest(){

        return new Quest();
    }

}


Spring 通过应用上下文装载bean的定义并把它们组装起来

上下文的分类

(ApplicationContext接口的实现类)
- AnnotationConfigApplicationContext 从一个或多个基于Java的配置类中加载Spring应用上下文
- AnnotationConfigWebApplicationContext 从一个或多个基于Java的配置类中加载SpringWeb应用上下文
- ClassPathXmlApplicationContext 从类路径下的一个或多个xml配置文件中加载上下文定义,把应用上下文的定义文件作为类资源
- FileSystemXmlApplicationContext 从文件系统下的一个或多个xml配置文件中加载上下文定义
- XmlWebApplicationContext 从web应用下的一个或多个xml配置文件中加载上下文定义

ApplicationContext context = new ClassPathXmlApplicationContext("xml文件路径");

ApplicationContext context = new AnnotationConfigApplicationContext(****.class);

ApplicationContext context = new FileSystemXmlApplicationContext("xml文件绝对路径C:/knight.xml");

Knight knight = context.getBean(Knight.class);

context.close();

切面简单实例

DI 能够让相互协作的组件保持松散耦合,而面向切面编程(aspect-oriented-programming AOP)允许你把遍布应用各处的功能分离出来形成可重用的组件(促使软件系统实现关注点分离)

例如吟游诗人歌颂骑士

public class Minstrel{

    private PrintStrean strean;

    public Minstrel(PrintStream strean){

        this.stream = stream;
    }

    public void singBeforeQuest(){//探险之前调用
        stream.println("the knight is brave");
    }

    public void singAfterQuest(){//探险之后调用

        stream.println("did embark on a quest");
    }

}

骑士

public class BraveKnight implement Knight{

    private QUest quest;
    private Minstrel minstrel;

    public BraveKnight(Quest quest,Minstrel minstrel){

        this.quest = quest;
        this.minstrel = minstrel;
    }

    public void embarkOnQuest(){
        minstrel.singBeforeQuest();
        quest.embark();
        minstrel.singAfterQuest();
    }


}

问题在于管理他的吟游诗人并不是骑士职责范围内的工作,而利用AOP可以声明吟游诗人必须歌颂骑士 而骑士本身并不用直接访问Minstrel的方法。

将Minstrel声明为一个切面


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="****"  ****>
    <bean id="knight" class="包名.类名">
        <constructor-arg ref="quest"/>  //注入构造器参数
    </bean>

    <bean id="quest" class="">
        <constructor-arg ref="#{T(System).out}"/>
    </bean>

    <bean id="minstrel" class="***.Minstrel">
        <constructor-arg ref="#{T(System).out}"/>
    </bean>


    <aop:config>

        <aop:aspect ref="minstrel">
            <aop:pointcut id="embark"
                expression="execution(* *.embarkOnQuest())" /> //定义切点


            <aop:breore //声明前置通知 pointcut-ref="embark"  method="singBeforeQUest" />

            <aop:after  //声明后置通知 pointcut-ref="embark"  method="singAfterQUest" />
        </aop:aspect>
    </aop:config>
</beans>




Spring Microservices in Action consists of 10 chapters and two appendixes: Chapter 1 introduces you to why the microservices architecture is an important and relevant approach to building applications, especially cloud-based applications. Chapter 2 walks you through how to build your first REST-based microservice using Spring Boot. This chapter will guide you in how to look at your microser- vices through the eyes of an architect, an application engineer, and a DevOps engineer. Chapter 3 introduces you to how to manage the configuration of your microser- vices using Spring Cloud Config. Spring Cloud Config helps you guarantee that your service’s configuration information is centralized in a single repository, versioned and repeatable across all instances of your services. Chapter 4 introduces you to one of the first microservice routing patterns: ser- vice discovery. In this chapter, you’ll learn how to use Spring Cloud and Net- flix’s Eureka service to abstract away the location of your services from the clients consuming them. Chapter 5 is all about protecting the consumers of your microservices when one or more microservice instances is down or in a degraded state. This chapter will demonstrate how to use Spring Cloud and Netflix Hystrix (and Netflix Ribbon) to implement client-side load balancing of calls, the circuit breaker pattern, the fallback pattern, and the bulkhead pattern. Chapter 6 covers the microservice routing pattern: the service gateway. Using Spring Cloud with Netflix’s Zuul server, you’ll build a single entry point for all microservices to be called through. We’ll discuss how to use Zuul’s filter API to build policies that can be enforced against all services flowing through the ser- vice gateway. Chapter 7 covers how to implement service authentication and authorization using Spring Cloud security and OAuth2. We’ll cover the basics of setting up an OAuth2 service to protect your services and also how to use JavaScript Web Tokens (JWT) in your OAuth2 implementation. Chapter 8 looks at how you can introduce asynchronous messaging into your microservices using Spring Cloud Stream and Apache Kafka. Chapter 9 shows how to implement common logging patterns such as log corre- lation, log aggregation, and tracing using Spring Cloud Sleuth and Open Zipkin. Chapter 10 is the cornerstone project for the book. You’ll take the services you’ve built in the book and deploy them to Amazon Elastic Container Service (ECS). We’ll also discuss how to automate the build and deployment of your microservices using tools such as Travis CI. Appendix A covers how to set up your desktop development environment so that you can run all the code examples in this book. This appendix covers how the local build process works and also how to start up Docker locally if you want to run the code examples locally. Appendix B is supplemental material on OAuth2. OAuth2 is an extremely flexi- ble authentication model, and this chapter provides a brief overview of the dif- ferent manners in which OAuth2 can be used to protect an application and its corresponding microservices.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值