Java EE Spring

Source: Internet
Author: User

1, Spring has shaken the Sun's Java EE Traditional heavyweight framework (EJB) with its own power, becoming the most used Java EE Enterprise application development Framework.

2, Spring is a layered Java EE application of a one-stop lightweight open-source framework, with control inversion (Ioc) and aspect-oriented programming (Aspect oriented Programming AOP) for the core, provides a performance layer springmvc, Many enterprise-class applications such as persistent layer Springjdbc and Business-level transaction Management.

3. Spring's mission: simplifying Java development. The goal is to achieve an easy-to-develop, easy-to-test and fully functional development Framework.

4, Spring Features:

    • Easy decoupling for simplified development:

Through the IOC container provided by spring, the dependencies between objects can be controlled by spring, avoiding excessive program coupling caused by hard coding;

    • Support for AOP Programming:

With the AOP functionality provided by spring, users can easily perform aspect-oriented programming, and many features that are not easily implemented with traditional object-oriented programming (OOP) can be easily addressed through aop;

    • Support for declarative transactions:

Improve the efficiency and quality of development by using Spring's declarative transactions to manage transactions flexibly;

    • Convenient program Testing
    • Easy integration of a variety of excellent frameworks
    • Reduce the difficulty of using Java EE APIs
    • Spring source code is a classic learning paradigm.

5. Control Inversion:

The so-called inversion of control is through the container to control the dependencies between business objects, rather than the traditional implementation, directly manipulated by the Code.

Control inversion is that the application itself is not responsible for the creation and maintenance of dependent objects, and the creation and maintenance of dependent objects is the responsibility of the external container. Thus control is transferred from the application to the external container, and the transfer of control is called Reversal. The benefit of control transfer is to reduce the degree of dependence between business Objects.

6. Dependency Injection (di): One of the key points of the IOC is to dynamically provide the other objects it needs to an object in the System's operation, which is achieved through DI.

Dependency injection is a way of assembling an application object that does not need to know where the dependency is coming from or how it is dependent, and the dependent object usually can only understand the injected object through the interface, which ensures low coupling.

The way of dependency Injection: constructor injection, method injection, interface Injection.

Note: the spring IOC container only supports constructors and method Injection.

7, spring comes with several kinds of container implementation, can be classified into two different types:

Beanfactory (bean factory): is the core interface of the spring framework, which provides the configuration mechanism of the advanced Ioc. Beanfactory makes it possible to manage different types of Java objects;

ApplicationContext (application context): It is built on the basis of beanfactory and provides more application-oriented Functionality. The beanfactory is generally called the IOC container, while the ApplicationContext is the application Context.

Note: the beanfactory belongs to the underlying package component, and the application is an Upper-layer package component that is intended for use by Developers.

8, Spring has three ways to get ApplicationContext application context Instances:

    • Classpathxmlapplication loads the context definition from the XML configuration file under the Classpath and treats the application context definition file as a class resource;
    • Filesystemxmlapplicationcontext reads the XML configuration file under the file system and loads the context definition;
    • Xmlwebapplicationcontext reads the XML configuration file under the Web application and loads the context definition;

The bean can be obtained from the IOC container by calling its Getbean () method from the ApplicationContext application context Instance.

Configure an instance of the <bean> corresponding to a bean component.

9. Assembly Bean

The so-called assembly refers to the behavior of creating collaborative relationships between application objects, which is also the essence of dependency injection;

Spring defines the way a file is configured to define the bean and its dependencies between beans and beans. Spring's ApplicationContext Application Context completes the Bean assembly work by loading and parsing the configuration File.

Bean configuration information is a Bean's metadata information, consisting of four facets: the implementation class (which obtains an instance through reflection), attributes, dependencies, behavior Configuration (callback functions for the life span and the process of the life cycle).

Spring supports multiple forms of bean configuration: xml-based configuration, annotation-based configuration, java class-based configuration.

10. Constructor Injection Bean

<constructor-arg value= "" > The spring container does not call the default constructor when it instantiates the bean, but instead calls the parameter Constructor.

<constructor-arg ref= "" > when the parameter type of the argument constructor is not all basic type and there is a reference type.

<factory-method> Assemble singleton patterns using a static method to instantiate a bean

11. Scope of Bean

In the spring container, all the beans are singleton by Default. When a container allocates a bean, it always returns the same instance of the Bean.

Sometimes you need to get a unique bean instance each time you request it, you can declare a scope for the Bean.

Singleton: (singleton mode);

Prototype: allows the definition of a bean to be instantiated any time;

Request: the session: conversation; global-session: global httpsession, A bean defines an instance.

12, when instantiating a bean, try not to perform some resource initialization operations, only simple assignment of initial value operation, and the operation of the initialization of the resources to the Init method to execute, resource cleanup operations into the destroy Method.

init-method= "" destroy-method= ""

Default-init-method Default-destroy-method

13. Bean Method Injection

The Get,set method must be added to the <property>,bean Component.

14. Internal Bean Injection:

Internal beans are not reusable, and internal beans are only available for one injection and cannot be referenced by other Beans.

15, Spring supports collection nesting, that is, the <list> or <set> element can also contain another <list> or <set> as its members; spring supports the assignment of NULL values, that is, using <null/ >

16. The new Spring3.0 feature introduces the spring expression language (spring expressions language,spel). Spel is a powerful, concise way of assembling a bean that assembles values into the Bean's properties or constructor parameters through an expression executed at run Time.

Spel expressions can refer to other beans, which are the same as the ref attribute reference Bean results, and the SPEL expression also supports referencing the Bean's properties and METHODS.

Spel can use the T () operator to refer to static classes, as well as properties and methods of static Classes.

The <util:list> element is defined by the Spring's util Namespace.

(.? []) implements the query collection member Operation. (. ^[]), (. $[]), Query the first eligible collection member and the last member that meets the query Criteria. (.! []) supports the implementation of a set projection Operation.

17. Spring provides two ways to simplify the XML configuration Bean:

Automatic assembly: let spring automatically identify how to assemble bean dependencies and reduce <constructor-arg><property>;

Auto-assemble Settings <bean> autowire properties.

You can add a Default-autowire property to the root element, and no by Default.

Priority: Default auto-assembly < Automatic assembly < display assembly

SPRING3 supports three types of annotations: the @autowired annotation that comes with it, jsr-330,jsr-250

@Autowired Annotations Specify automatic assembly

@Qualifier annotations specified to be assembled by name;

@Value annotations Specify basic properties and string types

@Scope Annotations Specify the scope;

@PostConstruct and @predestroy annotations specify initialization and destruction methods

Auto Detect: Let spring automatically identify which classes need to be assembled into beans, reducing <bean>;

<context:component-scan base-package> Scan Package

@Component

@Controller

18. AOP (Aspect oriented Programming) is a technique to realize the unified maintenance of program functions by pre-compiling and running-time dynamic agent for slicing Programming.

    • AOP is the continuation and beneficial complement of oop, as well as an important content in the spring framework, which is a derivative generic of functional programming.
    • AOP can isolate the various parts of business logic, thus reducing the coupling between parts of business logic, improving the reusability of programs, and improving the efficiency of Development.
    • Provides rich support for AOP in spring, allowing for the development of cohesive systems-level services and transaction management by separating the Application's business Logic.

19. the difference between AOP and OOP

    • Different design ideas;
    • OOP encapsulates the entities and attributes and behaviors of business processes in an abstract way to obtain clearer and more efficient logical unit Division.
    • AOP extracts the facets in the process of business processing, facing a step or stage in the process of processing in order to obtain the isolation effect of low coupling between parts of the logic process;
    • AOP is definitely not a substitute for oop, but is integrated with oop, which is a long, short-term complement.

20, crosscutting concerns: in software development, distributed in the application of many functions are called crosscutting concerns.

The goal of AOP is to isolate these crosscutting concerns from the business Logic.

The main functions of AOP are as follows: logging, performance statistics, security control, transaction processing, exception handling, etc.

21. Spring provides a solution to this repetitive code that cannot be abstracted through the vertical inheritance system (oop) by means of a horizontal extraction Mechanism. AOP is to make business logic code clearer by extracting the same code from each business logic code into a separate module by cutting it horizontally.

22. Connection point: A specific location where the program Executes. A class or a piece of program code has some specific points that have a boundary nature, and the specific point of the code becomes the connection Point. Note: Spring only supports connection points for methods, that is, before method calls, after method calls, and when methods throw exceptions, These programs perform point weaving enhancements;

Tangency: Each class typically has multiple connection points, and AOP needs to navigate to a specific connection point, and the way the connection point is positioned becomes the Pointcut. Note: spring tangency is defined by the Pointcut interface, which uses classes and methods as the query criteria for the connection point, and the SPRINGAOP rules parsing engine is responsible for parsing the query conditions set by the pointcut and locating the corresponding connection Points.

enhancement: enhancement is a piece of program code that is woven into the target class connection Point. In spring, the enhancement, in addition to describing a piece of program code, has another information related to the connection point-the orientation of the execution Point. By combining the azimuth information of the execution point with the Pointcut information, AOP can find the characteristics of the connection Point.

Beforeadvice: method call before Afterreturnadvice: return position after method call, Throws: throws Exception Position.

Target Object: It is an enhanced logic of the weaving target class, through aop, the business logic class only need to implement the code of Non-crosscutting logic, and performance monitoring, transaction management and other crosscutting logic can use AOP dynamic weaving into a specific connection Point.

Introduction: is a special enhancement, it adds some properties and methods for the class, even if a business class originally did not implement an interface, but also through the AOP referral function, dynamically add the interface to the business class implementation logic, so that the business class becomes the implementation of this interface class;

Weaving: the process of adding enhancement to the specific connection point of the target class, there are three ways: compiler weaving, class loading period weaving, dynamic Agent Weaving.

Proxy: when a class is augmented by aop, it produces a result class, which is a proxy class that incorporates the original and enhanced logic, and depending on the proxy, the proxy class is either a class with the same interface as the original class or a subclass of the original class, so the proxy class can be called the same way as the original class.

Facets: facets consist of tangent points and reinforcement or primers. It includes both the definition of the crosscutting logic and the definition of the connection Point. Note: The SPRINGAOP is responsible for the framework that implements the facets, which weave the crosscutting logic defined by the facets into the connection points specified by the Facets.

23, springaop: using a pure Java implementation, it does not require a specific compilation process, nor need a special class loader, it in the runtime through the proxy way to the target class into the enhanced Code. SPRINGAOP uses two proxy mechanisms: the JDK dynamic agent and the Cglib dynamic agent, which are SPRINGAOP underlying technologies.

24. Spring Enhanced Type

    • Pre-enhancement: beforeadvice, which indicates implementation enhancement before the target method is executed;
    • Post-build enhancement: afterreturningadvice, which indicates implementation enhancement after the target method is executed;
    • Surround Enhancement: methodinterceptor, which indicates implementation enhancements before and after the target method is executed;
    • Exception throw Enhancement: throwsadvice, which means that the enhancement is implemented after the target method throws an exception;
    • Introduction Enhancement: introductioninterceptor, which indicates that some new methods and properties are added to the target class.

25, proxyfactory

Spring provides the Proxyfactory agent factory to weave the enhancement into the target class, proxyfactory essence is the encapsulation of the underlying JDK dynamic agent and Cglib dynamic agent Technology.

26. XML configuration

Proxyinterfaces: the interface to be implemented by the agent;

Target-ref: Specifies the target class of the agent;

Interceptornames: a list of bean names that need to be woven into the target object

Optimize: enforces the use of Cglib dynamic Agent technology when set to True. (note: for Singleton agent, we recommend using Cglib proxy method; Other types of agents recommend using the JDK proxy METHOD)

27. Facets

Spring supports two methods of matching:

static method match: It only matches the method name signature and only once;

Dynamic method Match: It supports checking the value of the method in the runtime, and each method call must be judged that the dynamic matching has a great impact on performance and is not used Frequently.

Spring provides three types of Facets: the advisor General section, which contains only one advice class, the pointcutadvisor tangent plane, the advice and pointcut two classes, and the Introductionadvisor primer plane, A special section that corresponds to an enhanced interface.

28. Spring provides six types of tangency points: static method pointcuts, Dynamic method pointcuts, annotation pointcuts, expression pointcuts, process pointcuts, compound Pointcuts.

29, static Common method name matching tangent:

Staticmethodmatcherpointcutadvisor represents a static method to match a tangent, which defines a pointcut through a staticmethodmatcherpointcut definition of a pointcut through class filtering and method name matching, and the developer needs to inherit that Facet. and provides rules for matching class filtering and method Matching.

30. static regular expression matching tangent plane

In regexpmethodmatcherpointcutadvisor, you can match a regular expression in your configuration without having to write a special facet implementation class.

31. Dynamic tangency checks can have a significant impact on performance, so defining a static pointcut check in a dynamic Pointcut class can prevent unnecessary dynamic check operations, which greatly improves operational efficiency.

32, @Aspect annotations, The declaration of slices, configuration on the slice class; @Before, @After, @AfterThrowing annotations, Declaration of pre-enhancement, configuration on methods, @Around annotation surround enhancement, You must have a proceedingjoinpoint type parameter; @Pointcut (value= "") Annotation can define a pointcut, which can be referenced in other facet annotations.

Execution (return Type class Comprehensive. method name (formal parameter List))

* represents any character that matches an element in the context;

.. Represents any character, can represent a plurality of elements, but the expression of the class cannot be used alone, must and * coordination, in the representation of the parameters can be used alone;

+ represents all classes (including subclasses) that match the specified class by type, only following the class Name.

Restful

REST (representational State Transfer):

    • Representational state transfer, an architectural style of distributed hypermedia software;
    • A simple set of design principles, an architectural style (or pattern), is not a specific standard or architecture;
    • Based on the use of http, URIs and other existing widely popular protocols and standards, and supported by several core abstract concepts;
    • The essential regression of the web: a way to describe the web in a true manner;
    • Provides a way to differentiate between good practices and bad practices: to determine whether a particular practice is consistent with a web Schema.

Resources: resources can be anything that is expressed, not all resources can be obtained through the network, anything, as long as there is a reference to the necessary, is a resource, it can be a physical, can also be an abstract concept; usually a resource is something that can be stored on a computer and reflected as a Bitstream. In the web, you can think of it this way--the resource is something that the URI Identifies.

Means: The web is not a resource, but a representation of a resource, and there can be many different representations of a given resource.

Status: let the client maintain the application state, the server should not maintain the State.

Rest constraints and Styles:

    • The URI represents the resource;
    • Crud operations;
    • State representation transfer;
    • Non-state service;
    • HTTP status code;
    • Cache control;
    • Proxy;

The rest core is the architecture of a resource-centric model.

Rest Key Principles:

    • Define the ID for all resources, and you can use a URI identifier whether the resource on the Web represents a single data item, a collection of data items, a virtual or actual object, or a calculated Result.
    • Link all resources together; use links to guide resources that can be identified in any difficult situation.
    • Using standard methods; to enable client programs to collaborate with resources in the web, resources should correctly map four of the methods in the HTTP protocol to CRUD operations;
    • Multiple representations of resources, as much as possible to provide multiple representations of resources for different needs;
    • No State Communication. To do stateless communication often requires some redesign---cannot simply attach some session states to Uris.

Restful: an application or design that conforms to the rest constraints style and principles is Restful.

Spring supports restful style:

@RequestMapping and pathvariable annotations, support resource identification and URL mapping;

Contentnegotiatingviewresolver supports the use of different representations for different mime/content types;

Use a similar programming model to seamlessly integrate into the original MVC Layer.

Note: the form tag does not support submitting delete and put requests, the solution is as Follows:

(1): using SPRINGMVC to generate a hidden _method=put, and in the Web. XML Hiddenhttpmethodfilter with the use of the server side to change the post request to put request;

(2): you can use Ajax to send a request for a put, delete action on the Client.

Internet companies are becoming increasingly popular in providing restful forms of APIs for Third-party Calls.

Token (token) mechanism: It is used to solve the contradiction between stateless and Security. The implementation principle is as Follows:

    • The user sends the user name and password, requests the authentication through;
    • The server determines whether the user name and password are correct;
    • Server Authentication passed, return token and expiration time;
    • All requests carry the returned token to authenticate with token during expiration and use Restfulapi normally.

The SPRINGMVC package RESTFULAPI includes the following operations: token authentication mechanism, CRUD operations for encapsulated resources, exception handling.

Spring Conversion Request Method Filter Configuration

<filter>

<filter-name>HiddenHttpMethodFilter<

<filter-class>or.springframework.web.filter.HiddenHttpMethodFilter</filter-class>

<filter-mapping>

<filter-name>hiddenhttpmethodfilter

<servlet-name>springmvc

Java EE Spring

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.