Spring Knowledge Summary

Source: Internet
Author: User

About Spring

The spring framework was developed by Rod Johnson and the first edition of the spring Framework was released in 2004. Spring is a framework extracted from real-world development, so it accomplishes a lot of common steps in development, leaving developers with only the parts that are relevant to a particular application, thus greatly improving the efficiency of enterprise application development.

Spring summarizes the following advantages:

    • Low-intrusive design, code pollution is very low.
    • The commitment to write Once,run anywhere can be truly achieved, independent of various application servers, based on spring framework applications.
    • The spring IOC container reduces the complexity of business object substitution and improves decoupling between components.
    • Spring's AOP support allows for centralized management of some common tasks such as security, transactions, logs, and so on, providing better reuse.
    • Spring's ORM and DAO provide good integration with the third-party persistence layer framework and simplify the underlying database access.
    • Spring's high degree of openness does not force applications to rely entirely on spring, and developers are free to select part or all of the spring framework.

The diagram of the Spring Framework's composition is as follows:

Spring's core mechanism for managing beans

The main procedure is to access the Bean,applicationcontext in the container through the spring container, which is the most common interface of the spring container, which has the following two implementation classes:

    • Classpathxmlapplicationcontext: Searches for a configuration file from the class load path and creates a spring container based on the configuration file.
    • Filesystemxmlapplicationcontext: Searches the configuration file from the file system's relative path or absolute path, and creates a spring container based on the configuration file.
 Public class beantest{    publicstaticvoidthrows  exception{         New Classpathxmlapplicationcontext ("Beans.xml");         = Ctx.getbean (' person ', person.  Class);        P.say ();    }}
Eclipse uses spring

In IDE tools such as Eclipse, users can build their own User Library , and then put the spring jar packages into them, and of course can put the jar package directly in the project /WEB-INF/lib directory, but if used User Library , when the project is published, The jar file referenced by the user library needs to be published along with the app, which is to copy the jar used by the UI into the /WEB-INF/lib directory, because for a web app, the Eclipse deploys the web app without copying the user library's jar files to the /WEB-INF/lib next Manual replication is required.

Dependency Injection

The core features of the spring framework are two:

    • The spring container, as a super-large factory, is responsible for creating and managing all Java objects, which are called beans.
    • The spring container manages the dependencies between the beans in the container, and spring uses a method called dependency injection to manage the dependencies between the beans.

With dependency injection, you can inject not only normal attribute values for the bean, but also references to other beans. Dependency injection is an excellent decoupling method that allows beans to be organized together as configuration files, rather than being coupled in a hard-coded fashion.

Understanding Dependency Injection

Rod Johnson was the first person to attach great importance to managing a collaborative relationship with a Java instance in a configuration file, and he gave it a name: control reversal (inverse of control,ioc). Later Martine Fowler a different name for this way: Dependency Injection (Dependency injection), so whether it's a dependency injection or a control reversal, the meaning is exactly the same. When a Java object (the caller) needs to invoke the method of another Java object (a dependent object), there are usually two practices in traditional mode:

    1. The original procedure: the caller actively creates the dependent object and then invokes the method of the dependent object.
    2. Simple Factory mode: The caller first finds the factory of the dependent object and then takes the initiative to get the dependent object through the factory, and then invokes the method of the dependent object.

Notice the active word above, which inevitably leads to hard-coded coupling between the caller and the dependent object implementation class, which is very detrimental to the maintenance of the project upgrade. With the spring framework, the caller does not have to actively acquire the dependent object, and the caller simply accepts that the spring container assigns a value to the caller's member variable, so after using spring, The way the caller gets the dependent object is taken from the original initiative and becomes passively accepted-so Rod Johnson calls it control inversion.

In addition, from the spring container's point of view, the spring container is responsible for assigning the dependent object to the caller's member variable--equivalent to injecting the caller with the instance it relies on, so Martine Fowler is called a dependency injection.

Set Value Injection

A value injection is an IOC container that injects a dependent object through the setter method of a member variable. This injection method is simple and intuitive, so it is used extensively in spring's dependency injection.

Construction injection

A constructor is used to set up dependencies, which is called construct injection. In layman's terms, the constructor that drives spring to perform the specified parameters in the underlying reflection mode, when executing a constructor with parameters, can initialize the member variables with the constructor parameters-that is, the nature of the construction injection.

Comparison of two types of injection methods

Setting value injection has the following advantages:

    • More similar to the traditional JavaBean, program developers are more likely to understand and accept. It is more intuitive and natural to set the dependency relationship by setter method.
    • For complex dependencies, if you use construct injection, it can cause the constructor to be too bloated and difficult to read. When spring creates a bean instance, it needs to instantiate all of its dependent instances at the same time, resulting in performance degradation. These problems can be avoided by using the set value injection.
    • Multi-parameter constructors are more cumbersome, especially if some member variables are optional.

The advantages of construction injection are as follows:

    • Construction injection can determine the injection order of dependencies in the constructor, prioritizing the priority injection of dependency.
    • Construction injection is more useful for beans that do not require a change in dependency relationships. Because there is no setter method, all dependencies are set within the constructor without worrying about the subsequent code destroying the dependency.
    • Dependencies can only be set in the constructor, then only the creator of the component can change the dependencies of the component, and for the caller of the component, the dependencies within the component are completely transparent and more consistent with the high cohesion principle.

Attention:
It is suggested that the injection strategy should be based on value injection and structure injection as a supplement. As far as possible, there is no need for changes in the dependency of injection, the use of construction injection, while other dependency injection, then consider the use of value injection.

Beans in the spring container

For developers, the main thing for developers to do with the spring framework is to do two things: ① develop Bean;② configuration beans. For the spring framework, what it does is to create a bean instance based on the configuration file and invoke the Bean instance's method to complete the "dependency injection"-this is what is called the IOC's essence.

Scope of Bean in container

When you create a bean instance from a spring container, you can not only instantiate the bean instance, but also specify a specific scope for the bean. Spring supports five scopes such as:

    1. Singleton: Singleton mode, in the entire spring IOC container, the singleton-scoped Bean will generate only one instance.
    2. Prototype: Each time a bean of the prototype scope is obtained through the container's Getbean () method, a new bean instance is generated.
    3. Request: For an HTTP request, the request scoped Bean will generate only one instance, which means that within the same HTTP request, every time the program requests the bean, the same instance is always obtained. This scope is only really valid if you are using spring in a web app.
    4. For an HTTP session, the session-scoped bean will generate only one instance, which means that within the same HTTP session, every time the program requests the bean, the same instance is always obtained. This scope is only really valid if you are using spring in a web app.
    5. Global session: Each global HTTP session corresponds to a bean instance. In a typical case, only valid when using the Portlet context, and only in Web applications.

If you do not specify a scope for the bean, Spring uses the singleton scope by default. The creation and destruction costs of prototype-scoped beans are relatively high. The bean instances of the singleton scope can be reused once the results are created. Therefore, you should try to avoid setting the bean to prototype scope.

Injecting the partner bean with automatic assembly

Spring can automatically assemble a dependency between beans and beans, that is, instead of explicitly specifying a dependent bean using ref, the Spring container examines the contents of the XML configuration file and, according to some rules, injects a dependent bean into the caller's bean.
Spring Auto-assembly can be specified by the attributes of the <beans/> element default-autowire , which works for all beans in the configuration file, or it can <bean/> autowire only work on the bean by specifying its properties.

autowireAnd default-autowire can accept the following values:

    • no: Automatic assembly is not used. Bean dependencies must be defined by a REF element. This is the default configuration, which is discouraged from changing this configuration in a larger deployment environment, and explicitly configuring collaborators to get clearer dependencies.
    • byName: Automatic assembly According to the setter method name. The spring container finds all the beans in the container, finds out its ID and the setter method name removes the set prefix, and the bean with the same name as the lowercase first letter completes the injection. If no matching bean instance is found, spring does not inject any.
    • byType: Automatically assembled according to the parameter type of the setter method. The spring container finds all the beans in the container, and if there is exactly one bean type that matches the parameter type of the setter method, the bean is injected automatically; if more than one such bean is found, an exception is thrown; If no such bean is found, nothing will happen. The setter method is not called.
    • constructor: Similar to Bytype, the difference is the parameter used to automatically match the constructor. If the container cannot find exactly one bean that matches the constructor parameter type, an exception is thrown.
    • autodetect: The spring container uses the constructor or Bytype policy in its own discretion, based on the bean's internal structure. If a default constructor is found, then the Bytype policy is applied.

When a bean uses both automatic assembly dependencies and when explicitly specifying dependencies using ref, explicitly specified dependencies override automatic assembly dependencies, and automatic assembly is discouraged for large applications. Although the use of automatic assembly reduces the workload of the profile, it greatly kills the clarity and transparency of dependencies. The assembly of dependencies relies on the property name and property type of the source file, which causes the coupling between the bean and the bean to be reduced to the code level, which is not conducive to high-level decoupling.

<!-- you can exclude beans from automatic assembly by setting  - <  ID= ""  autowire-candidate= "false"/><!-- In addition to this, you can also specify in the beans element that the schema string is supported, and all beans ending in ABC are excluded from automatic assembly  - <  default-autowire-candidates= "*abc"/>
3 ways to create a bean use the constructor to create a bean instance

Using a constructor to create a bean instance is the most common case, and if you do not take a construction injection, the spring bottom calls the Bean class's parameterless constructor to create the instance, so the bean class is required to provide a parameterless constructor.

The default constructor is used to create the bean instance, and spring performs the default initialization for all properties of the bean instance, that is, the value of all primitive types is initialized to 0 or false, and the values of all reference types are initialized to null.

To create a bean using the static factory method

When you create a bean instance using the static factory method, the class property must also be specified, but at this point the Class property is not the implementation class for the specified bean instance, but rather the static factory class, which spring knows by which factory class to create the bean instance.

In addition to using the Factory-method property to specify the static factory method, spring will call the static factory method to return a bean instance, and once the specified bean instance has been obtained, the processing steps behind spring are exactly the same as creating the bean instance using the normal method. If the static factory method requires parameters, the element is used to <constructor-arg.../> specify the parameters of the static factory method.

Invoking an instance factory method to create a bean

The instance factory method has only one difference from the static factory approach: Calling the static Factory method requires only the factory class, whereas invoking the instance factory method needs a factory instance. When using the instance factory method, the element that configures the bean instance does not <bean.../> need a class attribute, and the instance factory method is configured to use the factory-bean specified factory instance.
<bean.../>you need to specify the following two properties when you create an element of a bean using the instance factory method:

    • Factory-bean: The value of this property is the ID of the factory bean.
    • Factory-method: This property specifies the factory method of the instance factory.

If you need to pass in a parameter when invoking an instance factory method, use the <constructor-arg.../> element to determine the parameter value.

Reconcile scoped beans that are not synchronized

When a singleton-scoped Bean relies on a prototype-scoped bean, it is not synchronized because the container initializes all of the containers when the spring container is initialized, singleton Bean singleton Bean depending on prototype Bean the So spring singleton Bean will be created before initialization- prototypeBean -and then created, and then singleton Bean prototype Bean injected singleton Bean .
There are two ways to resolve an out-of-sync approach:

    • Discard Dependency Injection: singleton-scoped beans each time a prototype-scoped bean is required, the active request of a new bean instance to the container guarantees that each injected prototype Bean instance is the most recent instance.
    • Method Injection: Method injection is usually injected using the lookup method, which is injected using the lookup method, which allows the spring container to rewrite the bean's abstraction or concrete method in the container, returning the result of finding the other bean in the container, which is usually one of the found beans non-singleton Bean . Spring implements these requirements by modifying the binary code of the client by using the JDK dynamic agent or the Cglib library.

The second approach is recommended, using method injection. In order to use the lookup method injection, the following two steps are generally required:

    1. The implementation class of the caller bean is defined as an abstract class and an abstract method is defined to obtain the dependent bean.
    2. <bean.../>adding child elements to the element <lookup-method.../> lets spring implement the specified abstract method for the caller Bean's implementation class.

Attention:

Spring uses a runtime dynamic enhancement to implement the <lookup-method.../> abstract method specified by the element, and if the target abstract class implements the interface, spring implements the abstract class using the JDK dynamic proxy and implements the abstract method for it, if the target abstract class does not implement the interface. Spring implements the abstract class with Cglib and implements an abstract method for it. The Cglib class library is already integrated in Spring4.0 's Spring-core-xxx.jar package.

Two types of post processors

Spring provides two commonly used post-processors:

    • Bean Post Processor: This post-processor will post-process the bean in the container and add additional strength to the bean.
    • Container Post Processor: This post processor will post-process the IOC container for enhanced container functionality.
Bean Post Processor

The Bean Post processor is a special kind of bean, which does not provide service to the outside, it can even not do without the id attribute, it is mainly responsible for post-processing of other beans in the container, such as the target bean in the container to generate agents, such as the bean is called after the processor. The Bean post processor will further enhance the bean instance after the bean instance has been successfully created. The Bean post processor must implement an BeanPostProcessor interface, and must implement two methods of the interface.

    1. Object postProcessBeforeInitialization(Object bean, String name) throws BeansException: The first parameter of the method is the bean instance that is about to be processed by the system, and the second parameter is the bean's configuration ID
    2. Object postProcessAfterinitialization(Object bean, String name) throws BeansException: The first parameter of the method is the bean instance that is about to be processed by the system, and the second parameter is the bean's configuration ID

Once the Bean post processor is registered in the container, the Bean post processor is automatically started and automatically works when each bean is created in the container, and the callback time for the two methods of the Bean post processor is as follows:

Note that if you BeanFactory are using as a spring container, you must manually register the bean post processor, and the program must obtain the Bean Post processor instance and then register it manually.

Beanpostprocessor BP = (beanpostprocessor) beanfactory.getbean ("BP"= (person) beanfactory.getbean ("person") ;
Container Post processor

The Bean Post processor is responsible for processing all bean instances in the container, and the container post processor is responsible for handling the container itself. Container after the processor must implement the BeanFactoryPostProcessor interface, and implement the interface of a method postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) of implementing the method is the process of the spring container, this processing can be the spring container custom extension, of course, the spring container can not do any processing.

Similarly, the container BeanPostProcessor ApplicationContext can be automatically detected after the processor, and the container is automatically registered after the processor. However, if used BeanFactory as a spring container, you must manually call the container after the processor to process the BeanFactory container.

Spring's "0 configuration" supports searching for bean classes

Spring provides several annotation to annotate spring beans:

    • @Component: Label a normal spring Bean class
    • @Controller: Labeling a Controller component class
    • @Service: Labeling a business logic component class
    • @Repository: Labeling a DAO component class

In the spring configuration file, configure the following configuration to specify the packages to be scanned automatically:

<base-package= "Edu.shu.spring.domain"/>
Configuring Dependencies using @resource

@ResourceLocated javax.annotation under the package, is one from the Java EE specification Annotation , which spring draws directly from, Annotation by using this Annotation to specify the collaborator Bean for the target bean. Use @Resource the <property.../> same effect as the ref attribute of an element.
@ResourceNot only can you modify the setter method, you can also directly modify the instance variables, if the use @Resource of modified instance variables will be more simple, when spring will be directly using the Java EE Specification field injection, at this time even setter method can not.

Customizing life cycle Behavior with @postconstruct and @predestroy

@PostConstructand @PreDestroy two annotation,spring from the Java EE specification, also located under the Javax.annotation package, are used to customize the life cycle behavior of the bean in the spring container. They are all used to modify the method without any attributes. Where the former modifies the method when the bean initializes the method, while the latter modifies the method when the bean is destroyed before the method.

Spring4.0 enhanced automatic assembly and precise assembly

Spring provides @Autowired annotations to specify automatic assembly, which @Autowired can be used to modify setter methods, common methods, instance variables, and constructors. When using @Autowired the label setter method, the Bytype automatic assembly policy is used by default. In this strategy, there are often multiple candidate bean instances that conform to the automatic assembly type, which can cause an exception at this time, and in order to achieve precise automatic assembly, Spring provides @Qualifier annotations that, by use @Qualifier , allow automatic assembly to be performed based on the Bean's ID.

Why AOP is required for spring AOP

AOP (Aspect Orient programming) is the aspect-oriented programming, as a complement to object-oriented programming, has become a relatively mature programming method. In fact, the time of AOP is not too long, AOP and OOP complement each other, aspect-oriented programming to break down the process of running the program into various facets.

AOP is specifically designed to address cross-focus issues in systems distributed across modules (different approaches), and in Java EE applications, some system-level services with crosscutting properties, such as transaction management, security checks, caching, object pool management, are often handled through AOP. AOP has become a very common solution.

Implementing AOP using AspectJ

ASPECTJ is a Java-based AOP framework that provides powerful AOP capabilities, and many other AOP frameworks draw on or adopt some of these ideas. It consists of two parts: one section defines how to express and define the syntax specification in AOP programming, and with this syntax, it is easy to use AOP to solve the problem of cross-concern in the Java language, and the other part is the tool part, including compiling, debugging tools and so on.

AOP implementations can be divided into two categories:

    1. Static AOP implementation: The AOP framework modifies the program at compile-time, that is, to enhance the target class and generate static AOP proxy classes, represented by ASPECTJ.
    2. Dynamic AOP implementation: The AOP framework dynamically generates an AOP proxy in the run phase to enhance the target object, represented by spring AOP.

In general, static AOP implementations have better performance, but special compilers are required. Dynamic AOP implementations are pure Java implementations, so no special compilers are required, but typically performance is slightly worse.

Basic concepts of AOP

Some terms for tangent-oriented programming:

    • Facets (Aspect): facets are used to organize multiple advice,advice that are defined in facets.
    • Connection point (Joinpoint): an explicit point in the execution of a program, such as a call to a method, or an exception thrown. In spring AOP, the connection point is always called by the method.
    • Enhanced Processing (Advice): An AOP framework performs enhanced processing at a particular pointcut. Handles types such as "Around", "before", and "after"
    • Pointcut (Pointcut): You can insert a connection point for enhanced processing. In a nutshell, when a connection point satisfies a specified requirement, the connection point is added with enhanced processing, which becomes a pointcut.
Spring's AOP support

The AOP agent in spring is generated and managed by the spring IOC container, and its dependencies are managed by the IOC container.
To use support in your app @AspectJ , Spring needs to add three libraries:

    • aspectjweaver.jar
    • aspectjrt.jar
    • aopalliance.jar

and make the following configuration in the spring configuration file:

<!--Start @aspectj Support -<Aop:aspectj-autoproxy/><!--Specify automatic search for bean components, automatic search of slice classes -<Context:component-scanBase-package= "Edu.shu.sprint.service">    <Context:include-filtertype= "Annotation"expression= "Org.aspectj.lang.annotation.Aspect"/></Context:component-scan>

Spring Knowledge Summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.