Spring (3): Spring Framework

A, Spring Framework understood bean

1.1, Spring bean in the scope of what?

  • singleton: single bean instance, Spring of the bean are single default embodiment;
  • prototype: every request to create a new bean instance;
  • request: Each HTTP request will generate a new bean, which is only valid in the current HTTP Request;
  • session: Each HTTP request will generate a new bean, which is only valid in the current HTTP the session;

1.2, the difference between @ Component and @Bean

Different (1) the role of objects: @Component Annotation Annotation role in the process of class scope @Bean

(2) different method of action: @Component annotated with class scanning path to automatically detect and automatically fitted into the Spring; @ Bean annotation usually labeled the annotation generation method defined in the bean, @ Beantold that a specific class Spring example, give me when you need it

(3) @ Bean annotation @ ratio  Component can only be used when the third-party libraries @ classes required when fitted into Spring: more customizable annotationsBean 

Note: @ ComponentScan annotation defines the path you want to scan to find out the identity of the class requires assembly automatic assembly into Spring bean container

//比如在SpringBoot启动类中,这样使用将扫描范围扩大到整个父包
@ComponentScan(“com.xxx.xx.springboot”)
@SpringBootApplication
public class SpringbootIn10StepsApplication {
...
}

1.3, a class declaration for the annotation of Spring bean of what? 

Use @ general Autowired annotation autowiring the bean, want to be identified for the class @ Autowired the bean class annotated automatic assembly, annotations may be implemented using the following:

  • @Component : Generic annotations, annotation can be any type of  Spring component. If a Bean do not know which layer belongs, you can use @Component annotation label.
  • @Repository : Dao i.e. persistence layer corresponding to layer, primarily used for database-related operations.
  • @Service : Corresponding to the service layer mainly related complex logic, need to use Dao layer.
  • @Controller : Spring MVC corresponding to the control layer, the primary user accepts the user request and returns the data to the call Service layer front page.

1.4, Spring bean in the life cycle

Recommended reading: https://www.cnblogs.com/zrtqsk/p/3735273.html

Spring Bean Lifecycle

Two, Spring framework which is used in design mode

Recommended reading: connection

  • Factory design pattern  : Spring by using the factory pattern  BeanFactory, ApplicationContext create bean object.

  • Proxy design pattern  : implement Spring AOP functionality.

  • Singleton design pattern  : Spring in Bean are single cases of default.

  • Template Method  : Spring In  jdbcTemplate, hibernateTemplate or the like to the end of the class Template database operations, they are used to model the template.

  • Packaging design pattern  : Our project need to connect multiple databases, and different customers will each visit to access different databases as needed. This model allows us to dynamically switch between different data sources according to customer demand.

  • Observer pattern:  the Spring event-driven model is the Observer pattern of a classic application.

  • Adapter mode  : Spring AOP enhancements or notification (Advice) to use the adapter mode, spring MVC is also used in the adapter mode adaptation Controller.

2.1, Spring in the factory pattern

Spring can be used by the factory pattern  BeanFactory or  ApplicationContext create a bean object

(1) Comparison between the two :

BeanFactory : Delayed implantation (when using a bean will be injected), less memory, fast start than BeanFactory occupancy;

ApplicationContext : When injected into the container starts, regardless useless to use, disposable create all bean, features than BeanFactory more commonly used.

(2) ApplicationContext realization of three categories:

  1. ClassPathXmlApplication: Document as the context classpath resources.

  2. FileSystemXmlApplication: Loaded from the file system XML file context definition information.

  3. XmlWebApplicationContext: Load context definition information from the Web system in XML files.

2.2, Spring of singleton

Some objects only one in the system, such as: the thread pool, cache, registry, log objects.

Spring default scope of the bean singleton is a single embodiment.

Spring single implementation example of (two kinds):

  • xml:<bean id="userService" class="top.snailclimb.UserService" scope="singleton"/>

  • annotation:@Scope(value = "singleton")

The principle:

Spring in by ConcurrentHashMap way of single-registry embodiment , single-mode embodiment, the core code is as follows:

// 通过 ConcurrentHashMap(线程安全) 实现单例注册表
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64);

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
        Assert.notNull(beanName, "'beanName' must not be null");
        synchronized (this.singletonObjects) {
            // 检查缓存中是否存在实例  
            Object singletonObject = this.singletonObjects.get(beanName);
            if (singletonObject == null) {
                //...省略了很多代码
                try {
                    singletonObject = singletonFactory.getObject();
                }
                //...省略了很多代码
                // 如果实例对象在不存在,我们注册到单例注册表中。
                addSingleton(beanName, singletonObject);
            }
            return (singletonObject != NULL_OBJECT ? singletonObject : null);
        }
    }
    //将对象添加到单例注册表
    protected void addSingleton(String beanName, Object singletonObject) {
            synchronized (this.singletonObjects) {
                this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));

            }
        }
}

2.3, Spring in proxy mode

SpringAOP can independent of those services, the lack of logic (transaction processing, log management, access control) to the common call service module encapsulates, in order to reduce the code reduce coupling, high scalability, maintainable. AOP is based on dynamic agent of.

 

2.4, Spring in the template method pattern

Template method defines a skeleton arithmetic operations, deferring some steps to subclasses, subclasses can not change such an algorithm Structures of certain steps of the algorithm to redefine.

In Spring JdbcTemplate, hibernateTemplate or the like to the end of the Template -based database operations, the method is to use the template pattern.

2.5, Spring in observer mode (publish - subscribe)

It represents a dependency between the object and the object, an object when the object changes dependent objects will respond.

Spring in the event-driven model is the classic mode of application observer

Spring time in the process:

(1) define an event

(2) define an event listener

(3) using the event publisher announced

2.6, Spring of the adapter mode

Adapter mode (Adapter) is an interface into another interface clients expect, those class interface adapter is not compatible with the work

(1) SpringAOP in adapter mode

Know AOP implementation is based on proxy mode, but inside the AOP enhanced or notification (Advice) use the adapter mode

(2) SpringMVC in adapter mode

In the Spring MVC, DispatcherServlet according to call request information  HandlerMapping,parsed corresponding to the request  after the Handler, the process starts HandlerAdapter adapterHandler。解析到对应的

Why use Spring MVC in adapter mode?

Controller SpringMVC in many species, different types of requests are processed by the Controller to a different method, if not then using the adapter mode, DispatcherServlet direct access to a corresponding type of Controller, needs its own judgment.

2.7, Spring in the decorator pattern

You can dynamically add properties to an object or behavior of some amount, more flexible than inheritance. When we need to modify the original function is not willing to amend the original code, design, sets out a Decorator in the original code.

Various streams in the JDK will use the (InputStream, FileInputStream , BufferedInputStream )

When Spring configuration DataSource, DataSource may be different databases and data sources using the decorator pattern can modify the existing code at least in accordance with customer demand for dynamic switching the data source , the Spring with the Wrapper or end Decorator basically a dynamic give objects to add additional responsibilities.

 

Three, Spring things

3.1, Spring in the management of things in several ways

(1) programmatic things: hard-coded in the code (not recommended);

(2) declarative things : Configuration (recommended) in the configuration file - divided into two

  • XML-based declarative things;
  • Based declarative things annotations.

Isolation level 3.2, Spring of things

TransactionDefinition  Interface 5 represent isolation level defines constants

(1) TransactionDefinition.ISOLATION_DEFAULT (using the database default isolation level)

Mysql REPEATABLE_READ default isolation level used; READ_COMMITTED isolation level Oracle defaults

(2) TransactionDefinition.ISOLATION_READ_UNCOMMITTED ( lowest isolation level ) - read uncommitted

Yet allowed to read the data could lead to dirty reads, phantom reads, non-repeatable read

(3) TransactionDefinition.ISOLATION_READ_COMMITTED - Oracle default - Read Committed

Allowing concurrent read data items already submitted, can prevent dirty reads, but phantom reads and non-repeatable reads still occur .

(. 4) TransactionDefinition.ISOLATION_REPEATABLE_READ - MySQL default - Repeatable Read

On the same field repeatedly reading the same result (unless modified itself things), you can prevent dirty reads and non-repeatable read, phantom read may still occur

(5) TransactionDefinition.ISOLATION_SERIALIZABLE ( highest level of isolation ) - serializable

Full compliance ACID isolation levels, followed by the implementation of all things, prevents dirty reads, non-repeatable read, phantom read . But the performance is not good is not commonly used

Note : MySQL and Oracle's default isolation level is not the same

 

Previous: the Spring Ioc Inversion of Control

Next: the Spring MVC fully understand

  Reference: "Spring Inside"

 

 

Published 52 original articles · won praise 116 · views 50000 +

Guess you like

Origin blog.csdn.net/RuiKe1400360107/article/details/103600484