天天看點

Spring架構中核心技術摘要

The IoC Container

The container then injects those dependencies when it creates the bean,依賴關系是通過容器去注入的,這就是IOC。

ApplicationContext

is a sub-interface of

BeanFactory

. It adds:

被spring容器管理的對象才叫Bean.

the objects that are managed by the Spring IoC container are called beans.

The

org.springframework.context.ApplicationContext

interface represents the Spring IoC container

Java-based configuration for their Spring applications.

Java configuration typically uses

@Bean

-annotated methods within a

@Configuration

class.

This linkage between

id

and

ref

elements expresses the dependency between collaborating objects.

<import/>

element to load bean definitions from another file or files.

在IOC容器中,bean被認為是

BeanDefinition

對象。

Within the container itself, these bean definitions are represented as

BeanDefinition

objects

you use the

id

attribute, the

name

attribute, or both to specify the bean identifiers. 沒有提供,Spring自動生成,規則為Bean Naming Conventions。

the

Class

property somewhat is equivalent to Java code with the

new

operator

Most Spring users prefer actual JavaBeans with only a default (no-argument) constructor and appropriate setters and getters modeled after the properties in the container.

DI exists in two major variants: Constructor-based dependency injection and Setter-based dependency injection.

兩種方式去注入依賴:1.構造器。2.setter方法。

讓IoC容器管理的三種方式:1. XML

bean

definitions;2.注解 annotated components (that is, classes annotated with

@Component

,

@Controller

, and so forth)。3.

@Bean

methods in Java-based

@Configuration

classes

it is a good rule of thumb to use constructors for mandatory dependencies and setter methods or configuration methods for optional dependencies.

The Spring team generally advocates constructor injection

單例的bean在容器被建立時就被建立。Beans that are singleton-scoped and set to be pre-instantiated (the default) are created when the container is created。其他範圍(scope)時,按需建立。Otherwise, the bean is created only when it is requested

If you use predominantly constructor injection, it is possible to create an unresolvable circular dependency scenario.構造器注入(mandatory )可能會導緻循環依賴。

a circular dependency between bean A and bean B forces one of the beans to be injected into the other prior to being fully initialized itself (a classic chicken-and-egg scenario).

XML Shortcut with the p(property)-namespace XML Shortcut with the c(constructor)-namespace

By default,

ApplicationContext

implementations eagerly create and configure all singleton beans as part of the initialization process. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.

Autowiring works best when it is used consistently across a project.

autowire–裝配引用,缺點:

  1. You cannot autowire simple properties such as primitives,

    Strings

    , and

    Classes

    (and arrays of such simple properties). This limitation is by-design.
  2. For this dynamic subclassing to work, the class that the Spring bean container subclasses cannot be

    final

    , and the method to be overridden cannot be

    final

    , either.

request :Only valid in the context of a web-aware Spring

ApplicationContext

.

This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object.

Spring架構中核心技術摘要

Spring’s concept of a singleton bean differs from the singleton pattern as defined in the Gang of Four (GoF) patterns book(per ClassLoader).

The scope of the Spring singleton is best described as being per-container and per-bean

in the case of prototypes, configured destruction lifecycle callbacks are not called,prototype僅僅相當于new。沒有額外的生命周期管理。

Singleton Beans with Prototype-bean Dependencies

CGLIB proxies intercept only public method calls! Do not call non-public methods on such a proxy. They are not delegated to the actual scoped target object.

To integrate your custom scopes into the Spring container, you need to implement the

org.springframework.beans.factory.config.Scope

interface

Customizing the Nature of a Bean

  • Lifecycle Callbacks,@PostConstruct,init-method
  • Aware Interfaces,

Internally, the Spring Framework uses

BeanPostProcessor

implementations to process any callback interfaces it can find

Using parent and child bean definitions can save a lot of typing. Effectively, this is a form of templating.

BeanPostProcessor

instances operate on bean (or object) instances. That is, the Spring IoC container instantiates a bean instance and then

BeanPostProcessor

instances do their work.

bean的後處理器(https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-extension-bpp-examples-hw)

BeanFactoryPostProcessor

operates on the bean configuration metadata.

factory.FactoryBean

interface for objects that are themselves factories.

The

@Required

annotation applies to bean property setter methods,Fine-tuning Annotation-based Autowiring with

@Primary

。。。@Qualifier

@Value

is typically used to inject externalized properties:

repository (also known as Data Access Object or DAO)

the

@RestController

annotation from Spring MVC is composed of

@Controller

and

@ResponseBody

.

To autodetect these classes and register the corresponding beans, you need to add

@ComponentScan

to your

@Configuration

class,

However, regular

@Bean

methods in

@Configuration

classes need to be overridable — that is, they must not be declared as

private

or

final

.

component‘s bean name is generated by the

BeanNameGenerator

strategy known to that scanner

the default bean name generator returns the uncapitalized non-qualified class name

The

@Bean

annotation is used to indicate that a method instantiates, configures, and initializes a new object to be managed by the Spring IoC container.

Instantiating the Spring Container by Using AnnotationConfigApplicationContext

@bean:By default, the bean name is the same as the method name,This functionality can be overridden with the

name

attribute.

There are a few restrictions due to the fact that CGLIB dynamically adds features at startup-time. In particular, configuration classes must not be final.

the

@Import

annotation allows for loading

@Bean

definitions from another configuration class

The word, “environment,” can mean different things to different users,@Profile,also applied to method level

A

PropertySource

is a simple abstraction over any source of key-value pairs

If a bean that implements the

ApplicationListener

interface is deployed into the context, every time an

ApplicationEvent

gets published to the

ApplicationContext

, that bean is notified.

You should use an

ApplicationContext

unless you have a good reason for not doing so

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#resources

Aspect-oriented Programming (AOP) complements Object-oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect.

AOP is used in the Spring Framework to:

  • Provide declarative enterprise services. The most important such service is declarative transaction management.
  • Let users implement custom aspects, complementing their use of OOP with AOP.

In the Spring Framework, an AOP proxy is a JDK dynamic proxy or a CGLIB proxy.

Spring AOP currently supports only method execution join points . Field interception is not implemented.Spring AOP defaults to using standard JDK dynamic proxies for AOP proxies.It is good practice to program to interfaces rather than classes

Spring AOP is proxy-based

首先,其次。

Pojo pojo = (Pojo) factory.getProxy();
// this is a method call on the proxy!
pojo.foo();
           
Spring架構中核心技術摘要

this.bar()直接代用不會觸發切面。

@Pointcut(比對的方法):you can think of a pointcut as matching the execution of methods on Spring beans

The execution of any method defined in the service package:
	execution(* com.xyz.service.*.*(..))

           

Advice:runs before, after, or around method executions matched by the pointcut.

If the target object to be proxied implements at least one interface, a JDK dynamic proxy is used. All of the interfaces implemented by the target type are proxied. If the target object does not implement any interfaces, a CGLIB proxy is created(缺點:容不下final方法).

The SpEL classes and interfaces you are most likely to use are located in the

org.springframework.expression

package and its sub-packages, such as

spel.support

.

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Hello World'"); 
String message = (String) exp.getValue();
           

the syntax to define the expression is of the form

#{ <expression string> }

. @Value

Spring’s

Resource

interface is meant to be a more capable interface for abstracting access to low-level resources.