Java must-see Spring knowledge Summary! There's more to this than I lose!

Source: Internet
Author: User
Tags aop java web

Featured places in the past period

"1" Java Web Technology Experience Summary

"2" 15 top-level Java multithreading questions and answers, come and take a look.

"3" the interviewer most like to ask 10 Java face questions

"4" from the zero-speaking Java, give you a clear way to learn! What to learn!!

"5" Benefits: 100G Java Full learning video sent for free

The spring framework is created because of the complexity of software development. Spring uses the basic javabean to accomplish things that could have been done by EJBS before. However, the use of spring is not limited to server-side development. From the standpoint of simplicity, testability, and loose coupling, most Java applications can benefit from spring.

Spring Benefits:

Low-intrusive design, code pollution is very low;

Independent of a variety of application servers, based on the application of Spring framework, can really realize the promise of write once,run anywhere;

Spring's 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;

Pring'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 composition of the Spring Framework diagram:

The core mechanism of spring

Management Bean

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: Search for configuration files from the class load path and create a spring container based on the configuration file;

Filesystemxmlapplicationcontext: Search for a configuration file from the file system's relative path or absolute path, and create a spring container based on the configuration file

Publicclassbeantest{publicstaticvoidmain (String args) throws exception{applicationcontext CTX = Newclasspathxmlapplicationcontext ("Beans.xml"); Person p = ctx.getbean ("person", person.class); P.say; } }

Eclipse using Spring

In IDE tools such as Eclipse, users can build their own user library and then put the Spring jar package in it, but can also put the jar package directly in the project's/web-inf/lib directory, but if you use the 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 the jar used by the Subscriber library to be copied to the/web-inf/lib directory, because for a WEB application, When you deploy a WEB app, Eclipse does not copy the user library's jar files to/web-inf/lib and requires manual replication.

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 of the 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:

Original procedure: The caller actively creates the dependent object and then invokes the method of the dependent object;

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. After using the spring framework, the caller does not have to actively acquire the dependent object, as long as the caller passively accepts that the spring container assigns a value to the caller's member variable, so that after using spring, the caller acquires the dependent object from the original active acquisition 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 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 up 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:

The construction injection can determine the injection order of dependency in the constructor, and the priority injection is the priority 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 breaking the dependency relationship;

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.

Notes suggest that the injection strategy is based on value injection, and constructs 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:

Singleton: Singleton mode, in the entire spring IOC container, the singleton-scoped Bean will generate only one instance;

Prototype: Each time a bean of the prototype scope is obtained through the container's Getbean method, a new bean instance is generated;

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. The scope is truly valid only if you are using spring in a web app;

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. The scope is truly valid only if you are using spring in a web app;

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 element's Default-autowire property, which works on all beans in the configuration file, or by the Autowire attribute of the element, which only works on the bean.

Autowire and 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, and in a larger deployment environment it is discouraged to change this configuration, and explicit configuration of the collaborators can 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. Setter methods are not invoked;

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;

The Autodetect:spring container, based on the internal structure of the bean, uses the constructor or Bytype policy at its own discretion. 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. Dependency assembly relies on the property name and the property type of the source file, which causes the coupling between bean and bean to be reduced to the code level, which is disadvantageous to high-level decoupling;

<!--by setting the bean can be excluded from automatic assembly--><beanid= "" Autowire-candidate= "false"/><!--in addition, can also be specified in the beans element, Supports pattern strings, all beans ending in ABC are excluded from automatic assembly--><beansdefault-autowire-candidates= "*abc"/>

3 ways to create a bean:

To create a bean instance using the constructor

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, use the < constructor-arg.../> element to 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 < bean.../> element of the configuration bean instance does not require the class attribute, and the instance factory method is used to specify the factory instance using Factory-bean. The following two properties need to be specified when creating a bean's < bean.../> element with an 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 parameters when invoking an instance factory method, use the < constructor-arg.../> element to determine the parameter values.

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 the singleton beans in the container when the spring container is initialized, because Singleton The Bean relies on the prototype bean, so spring will create the prototypebean--before initializing the singleton Bean, and then the Singleton Bean will be created, then prototype Beans are injected into the 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 instance of the prototype bean is the latest instance;

Using 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 in the container with an abstract or concrete method that returns the result of finding the other bean in the container, which is usually a 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:

The implementation class of the caller bean is defined as an abstract class, and an abstract method is defined to obtain the dependent Bean2. Add < lookup-method.../in < bean.../> elements > The child element lets spring implement the specified abstract method notes for the caller Bean's implementation class;

Spring implements the abstract method specified by the <lookup-method.../> element in a run-time dynamic enhancement, 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 an 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 extra 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 the 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 the system is about to post-process. The second parameter is the bean's configuration Id2.object postprocessafterinitialization (Object Bean, String name) throws Beansexception: The first parameter of the method is the bean instance that the system is about to process, and the second parameter is the bean's configuration ID.

Once the Bean post processor has been registered in the container, the Bean Post processor will automatically start and work automatically when each bean is created in the container, and the callback time for the two methods of the bean after the processor

Note that if you use beanfactory as the spring container, you must manually register the bean post processor, and the program must obtain the Bean Post processor instance and register it manually.

Beanpostprocessor BP = (beanpostprocessor) beanfactory.getbean ("BP"); Beanfactory.addbeanpostprocessor (BP); Person P = (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. The container after the processor must implement the Beanfactorypostprocessor interface and implement a method of the interface Postprocessbeanfactory (configurablelistablebeanfactory Beanfactory) The method body that implements the method is the processing of the spring container, which can customize the spring container and, of course, do nothing with the spring container.

Similar to Beanpostprocessor,applicationcontext can automatically detect containers in the container after the processor, and automatic registration of the container after the processor. However, if you use Beanfactory as the spring container, you must manually call the container post processor to process the Beanfactory container.

Spring's "0 configuration" support

Search Bean class:

Spring provides several annotation to annotate spring beans

@Component: Labeling 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 automatically scanned package

<context:component-scan base-package= "Edu.shu.spring.domain"/>

Use @ Resource Configuration Dependencies

@Resource is located under the Javax.annotation package and is a annotation,spring from the Java EE specification that directly draws on the annotation, specifying the collaborator Bean for the target bean by using the annotation. Using @resource has the same effect as the ref attribute of the < property.../> element. @Resource can not only modify the setter method, you can also directly modify the instance variables, if you use @resource to modify the instance variable 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

The @PostConstruct and @predestroy are also located under the Javax.annotation package and are the two annotation,spring from the Java EE specification that 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, @Autowired can modify setter methods, common methods, instance variables and constructors, and so on. When using the @autowired callout 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 Spring provides @qualifier annotations for precise automatic assembly, allowing automatic assembly based on the Bean's ID by using @qualifier.

Spring's AOP

Why do I need 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, generate static AOP proxy classes, and AspectJ to represent 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 to be 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. Processing has "around", "before" and "after" and other types;

Pointcut (Pointcut): You can insert a connection point for enhanced processing. In short, when a connection point satisfies a specified requirement, the connection point is added with enhanced processing, which becomes the point of entry for the AOP support of spring;

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 @aspectj support in your app, 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= "Cn.javastack.service">          <Context:include-filtertype= "Annotation"expression= "Org.aspectj.lang.annotation.Aspect"/></Context:component-scan>

Recommended for previous period

"1" Java Web Technology Experience Summary

"2" 15 top-level Java multithreading questions and answers, come and take a look.

"3" the interviewer most like to ask 10 Java face questions

"4" from the zero-speaking Java, give you a clear way to learn! What to learn!!

"5" Benefits: 100G Java Full learning video sent for free

My public number, welcome attention! Get more technical dry foods!

Java must-see Spring knowledge Summary! There's more to this than I lose!

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.