The spring knowledge point of Java

Source: Internet
Author: User
Tags wrapper

The concept of 1.AOP is aspected oriented programming aspect-oriented Programming.

Benefit: AOP breaks the program down into various aspects or concerns. This makes it possible to modularize, quite horizontally on the slitting. It solves crosscutting (crosscut) issues such as transactions, security, logging, and other crosscutting concerns that are not well addressed by OOP and procedural methods.

There are several ways to implement Aop:

1. In Spring 1.2, AOP is implemented through proxyfactorybean, i.e. through dynamic proxies, aspect must inherit methodbeforeadvice,methodafteradvice, etc.

2. Spring 2.0 AOP needs to be changed to the FBI class, and it does not need to implement some interfaces

3. Three using annotations (@AspectJ) for AOP


The difference between AOP and oop:

1. aspect-oriented Programming AOP focuses on a step or stage of the business process, emphasizing reducing the coupling between modules, and making the code more Portable.

2. object-oriented Programming (OOP) is the encapsulation of methods and properties for entities extracted in business Analysis.

It can also be said that AOP is a business-oriented field of verbs, oop for the field of Nouns.

An important feature of AOP is source code independence, which means that if we reference an AOP component in our system, even if we remove the component, the system code should be able to compile. To achieve this, you can use the dynamic proxy Mode.


AOP is implemented in the "aspect" code set in the system; AOP helps to improve system maintainability; AOP is a design pattern, and spring provides an implementation;


2.propagation_required

If there is no current transaction, create a new transaction, if one is already present, join the Transaction. This is the most common choice.

Propagation_supports

Supports the current transaction and is executed in a non-transactional manner if no transaction is currently in Use.

Propagation_mandatory

Throws an exception if no transaction is currently in use for the current Transaction.

Propagation_requires_new

Creates a new transaction, suspending the current transaction if the transaction currently Exists.

propagation_not_supported

Executes the operation in a non-transactional manner, suspending the current transaction if a transaction is currently Present.

Propagation_never

Executes in a non-transactional manner, throwing an exception if a transaction is currently Present.

propagation_nested

Executes within a nested transaction if the transaction is currently Present. If there is currently no transaction, perform a similar operation as Propagation_required.


3.Spring of Dependency Injection:

Dependency injection typically has the following two types: set injection and construct injection:

Construction injection can determine the injection order of dependencies in the constructor, priority-dependent injection

SetPoint injection refers to an IOC container that uses a setter method of attributes to inject a dependent instance. This injection method is simple and intuitive


4.DispatcherServlet is the implementation of the front-end controller design pattern, provides a central access point for spring Web mvc, and is responsible for assigning responsibilities,

and seamlessly integrates with the spring IOC container to get all the benefits of Spring.

Dispatcherservlet is mainly used for responsibility scheduling, itself mainly for the control process, the main responsibilities are as Follows:

1, File Upload parsing, If the request type is multipart will be through the Multipartresolver file upload parsing;

2, through the handlermapping, map the request to the processor (return a handlerexecutionchain, which includes a processor, multiple handlerinterceptor interceptors);

3. Support multiple types of processors (processors in Handlerexecutionchain) through handleradapter;

4, through the Viewresolver analytic logical view name to the concrete view realization;

5, localization analysis;

6, rendering the specific views, etc.;

7, if the execution process encountered an exception will be given to Handlerexceptionresolver to Resolve.

Spring Mvc's Core Controller Dispatcherservlet It is responsible for receiving HTTP requests, loading configuration files, initializing the upper and lower Application object Applicationcontext.


5. In Java ee, using a servlet filter, you need to configure the <filter> (filter),<filter-mapping> (filter map) element in Web. xml.


The method of the 6.Servlet interface has the init method.

Servlet methods include init (), destroy (), doget (), doPost (), and so On.


The core ideas in the 7.Spring framework include dependency injection, control inversion, and Aspect-oriented.


8. How to get a connection pool in the spring framework:

DBCP Data source

C3P0 Data source

Spring's data source Implementation class (drivermanagerdatasource)

Get Jndi Data source


9. In a servlet, the way to achieve redirection is to:

The Sendredirect method using the Javax.servlet.http.HttpServletResponse interface.

The Sendredirect method is redirect

The forward method is request forwarding


10.sendRedirect ():

redirect, let the customer complete the work, namely the Address bar changes, can turn to external resources. The method parameter is String. Use relative URLs as Parameters. The full URL is established with the relative original Url. The relative web app is built without a/.

Forward ():

Request dispatch, Internal forwarding of the server, is transparent to the customer (the address bar does not change).

Based on the servlet api, you can use the forward method to change the address in the Address bar when steering is not displayed


The 11.1. Java Servlet API refers to the Session mechanism to track the state of a customer. The Javax.servlet.http.HttpSession interface is defined in the servlet API, and the servlet container must implement this interface.

2. When a session begins, the servlet container creates a HttpSession object, and the servlet container assigns a unique identifier, called the Session ID, to HttpSession. The Servlet container stores the Session ID as a Cookie in the Client's browser. Each time a customer makes an HTTP request, the Servlet container can read the session ID from the HttpRequest object and then find the corresponding HttpSession object based on the session ID to obtain the Customer's status Information.

3. When the client browser prohibits the Cookie,servlet container from getting the Session ID as a Cookie from the client browser, the customer status cannot be Tracked.

Another mechanism for tracking the session is presented in the Java Servlet API, where the client browser does not support the Cookie,servlet container to rewrite the URL of the client request and add the session ID to the URL Information.

4. HttpServletResponse interface provides a way to rewrite urls: public java.lang.String encodeurl (java.lang.String Url)

The implementation mechanism of this method is:

first, determine whether the current Web component is session-enabled, and if not, return the parameter URL directly.

Again determine whether the client browser supports cookies, if a cookie is supported, directly returns the parameter url, if the cookie is not supported, the Session ID information is added to the parameter url, and then the modified URL is returned.

We can modify the links in the webpage to solve the above problems:

Before Modification:

<a href= "maillogin.jsp" >

After modification:

<a href= "<%=response.encodeurl (" maillogin.jsp ")%>" >


12. Types of Transaction attributes: propagation behavior, isolation level, read-only, and transaction timeouts

A) The propagation behavior defines the transaction boundary of the invoked Method.

The meaning of communication behavior

1.propergation_mandatory

Indicates that the method must be running in a transaction and throws an exception if the current transaction does not exist

2.propagation_nested

Indicates that the method should run in a nested transaction if the current transaction exists.

3.propagation_never

Indicates that the method cannot run in a transaction, or throws an exception

4.propagation_not_supported

Indicates that the method cannot run in a transaction, and the method will be suspended if a transaction is currently present

5.propagation_required

Indicates that the current method must be running in a transaction, and if a transaction is currently present, the method runs in this transaction, otherwise a new transaction is created

6.propagation_requires_new

Indicates that the current method must be running in its own transaction, and if a transaction is currently present, the transaction will be suspended while the method is running

7.propagation_supports

Indicates that the current method does not need to run in a transaction, but if a transaction already exists, the method can also run in this transaction

B) Isolation Level

There are 3 side effects that can be generated when manipulating data, namely Dirty reading, non-repeatable reading, and Phantom Reading.

To avoid these 3 side effects, 4 Isolation levels are defined in standard SQL statements.

are uncommitted, read-committed, repeatable-read, serializable, respectively.

There are 5 isolation levels available in spring transactions that correspond to the 4 isolation levels defined in SQL.

As follows:

Isolation level significance

1.isolation_default using the default isolation level of the Back-end database

2.isolation_read_uncommitted

Allows reading uncommitted data (corresponding to uncommitted reads), which can result in dirty reads, non-repeatable reads, Phantom reads

3.isolation_read_committed

Allows you to read data from another committed transaction in one transaction (corresponding read-committed). Can avoid dirty reading, but cannot avoid non-repeatable reading and phantom reading

4.isolation_repeatable_read

It is not possible for a transaction to update data that has been modified by another transaction but has not yet committed (rolled Back) (corresponding to repeatable reads).

Can avoid dirty reads and non-repeatable reads, but cannot avoid phantom reads

5.isolation_serializable

This isolation level is where all transactions are performed in one execution queue, sequentially, rather than parallel (corresponding to serializable). You can avoid dirty reading, non-repeatable reading, and Phantom Reading. however, This isolation level is inefficient, so it is not recommended unless it is necessary.

C) read-only

If all operations on a database in a transaction are read-only, that is, these operations read only the data in the database and do not update the data, then the transaction should be set to Read-only (read_only_marker), which is more advantageous for the database to Optimize.

Because read-only optimizations are implemented by the database after a transaction is started, only those that have the potential to initiate new transactions (propagation_nested, propagation_required, propagation_required_new ) is meaningful only if the transaction of the method is marked as Read-only.

If hibernate is used as a persistence mechanism, then when the transaction is marked as read-only, Hibernate's flush mode is set to Fulsh_never to tell hibernate to avoid unnecessary synchronization with the database and to defer all updates to the end of the Transaction.

D) Transaction Timeout

If a transaction is running for a long time, in order to avoid wasting system resources, set a valid time for the transaction to wait for a few seconds to automatically roll Back.

As with the "read-only" property set, Transactional valid attributes also need to be propagated to those with the potential to start new things

The behavior of the method of the transaction is marked as read-only to make Sense.


Description of the IOC in the 13.Spring feature:

The so-called "inversion of control" means that control is transferred from the application code to the external container, that is, the transfer of control Rights.

The IOC moves the responsibility of controlling the creation into the framework, separating it from the application Code.

When using the spring IOC container, only the objects required by the component are indicated, and at runtime the IOC container of spring is provided to it based on the XML configuration Data.


14.Spring Frame module, Seven modules, as Follows:

1. The Spring Core:core package is the most fundamental part of the framework, providing IOC and dependency injection Characteristics. The basic concept here is beanfactory, which provides a classic implementation of the factory pattern to eliminate the need for procedural singleton patterns and really allows you to isolate dependencies and configurations from the program Logic.

2.Spring context: The context package, built on the core package, provides a framework for object access, Some like the Jndi registrar. The context wrapper package is characterized by the beans package and adds support for internationalization (i18n), event propagation, the way resources are loaded, and the transparent creation of the context, such as through a servlet container.

3. Spring Dao:dao (Data Access Object) provides a JDBC abstraction layer that eliminates lengthy JDBC encoding and resolves database vendor-specific error codes. also, the JDBC package provides a better declarative transaction management approach than programmatic, not only for specific interfaces, but also for all POJOs (plain old Java objects).

The 4.Spring Orm:orm package provides an integrated layer of commonly used "object/relationship" mapping Apis. These include jpa, JDO, Hibernate, and IBatis.

With the ORM package, you can mix all spring-provided features for object/relationship mapping,

Simple declarative transaction management, as mentioned Earlier.

The AOP package for 5.Spring Aop:spring provides an aspect-oriented programming implementation that conforms to the AOP Alliance specification, allowing you to define, for example, method interceptors (method-interceptors) and pointcuts (pointcuts), logically, Thereby weakening the functional coupling of the code, clearly separated away. also, with the Source-level metadata feature, you can incorporate various behavioral information into your Code.

Web Packages in 6.Spring web:spring provide the underlying integration features for web development, such as multi-party file uploads, and the use of servlet listeners for IOC container initialization and web-based Applicationcontext. When using spring with webwork or struts, This package enables spring to be combined with other frameworks.

The MVC wrapper package in 7.Spring Web Mvc:spring provides a model-view-controller (MVC) implementation of the Web Application. The spring MVC Framework does not simply provide a traditional implementation, it provides a clear separation model between the domain model code and the Web Form. also, Other features of the spring framework can be used.


15.spring description of the Bean's life cycle:

If the Bean class has implemented the Org.springframework.beans.factory.BeanFactoryAware interface,

The factory calls the Setbeanfactory () method to pass in to the factory itself.

You can use the "init-method" property in the bean definition File.

Rg.springframework.beans.factory.DisposableBean interface,

Then execute his destroy () Method.


Created: <bean name= "" class= "" Extra Properties >

Initialize: Configure Init-method/implementation Interface Initializingbean

Call: Context.getbean (), Making a call to the method

Destroy: Configure destroy-method/to Implement Disposablebean Interface.


The primary purpose of the DAO (data Access Object) support provided by 16.Spring is to facilitate the use of different data access technologies in a standard manner.

simplifies the development of DAO Components.

Spring provides a set of abstract DAO classes for you to Extend. These abstract classes provide a number of ways to simplify code Development. The use of the IoC container provides decoupling between the DAO components and the business logic Components. All DAO components are injected into the business logic component by the container, and their business components do not need to be concerned with the implementation of DAO Components. Interface-oriented programming and the use of DAO patterns improve the decoupling between system components,

Reduces the cost of system Refactoring.

Convenient transaction management: Spring's Declarative Transaction management dynamics are Method-level.

Exception wrapping: Spring can wrap hibernate anomalies and change them from checkedexception

For runtimeexception; Developers can choose to handle unrecoverable exceptions in the data at the right level,

So as to avoid cumbersome catch/throw and abnormal statements.

The DAO provided by spring supports jdbc, jdo, and Hibernate.


The difference between 17.spring MVC and Struts2:

1.spring MVC is a method-based design, and Struts2 is a class-based design.

2.STRUTS2 has its own interceptor mechanism, and Spring MVC uses an independent AOP Approach.

The 3.spring MVC approach is essentially independent of the request response data, struts2 All action variables are Shared.

4. Mechanism: Spring MVC is the gateway to the servlet, and Struts2 is the Filter.

Some additional knowledge:

The Filter implements the Javax.servlet.Filter interface, which is configured in Web. XML with a label specifying which

The filter implementation class filters which URL links. Initialize only when the Web is Started.

The filter process is linear, and after the URL has passed, after checking, the original process can continue to execute downward,

Is received by the next filter, servlet, etc., and the servlet does not continue to pass down after Processing.

The filter function can be used to keep the process going as it is, or to dominate the process, and the Servlet's functionality is primarily used to dominate the PROCESS.

Features: You can modify the header of request and response before responding, and only forward requests, not respond directly.

Filter can be used for character encoding filtering, detection of User Login filtering, prohibit page caching, etc. "servlet, servlet process is short, after the URL has been processed, then return or turn to a specific page of their own." It is primarily used to control the business before it is Processed.

What about the listener? We know that servlets, filter are all for urls, and listener is for objects, such as the creation of a session, the occurrence of session.setattribute, something to do when such an event Occurs. 》

5. Performance: spring will be slightly faster than struts. Spring MVC is a method-based design, and Sturts is class-based, each time a request is made, an action is instantiated, each action is injected into the attribute, and spring is based on a method that is more granular (granularity-level things compare sychronized and lock), But be careful to control the data like in the Servlet.

SPRING3 MVC is a method-level interception that, after intercepting a method, injects the request data into a parameter based on annotations, and in Spring3 mvc, a method corresponds to a request Context. The STRUTS2 framework is a class-level intercept, creating an action every time a request is made, and then invoking the setter getter method to inject the data from the request; struts2 actually deals with the request through the setter Getter Method. ; in struts2, an Action object corresponds to a request Context.

6. Parameter passing: struts is a parameter that can be accepted with attributes when it is accepted, which means that the parameters are shared by multiple methods.

7. Design Thinking: struts more in line with OOP programming ideas, Spring is more cautious, extended on the Servlet.

8. Intercepter (interceptor) Implementation mechanism: struts has its own interceptor mechanism, Spring MVC uses a separate AOP Approach. This leads to the configuration file of struts is still larger than spring mvc, although the configuration of struts can inherit, so I think, in terms of use, spring MVC use more concise, development efficiency Spring MVC is really higher than struts2. Spring MVC is a method-level intercept, a method that corresponds to a request context, and a method that corresponds to a url, so it is easy to implement a restful URL spring3 mvc from the schema itself. Struts2 is Class-level interception, A class corresponds to a request context, and implementing a restful URL is laborious because a method of struts2 action can correspond to a url, and its class properties are shared by all METHODS. It is also not possible to identify the method that it belongs to by annotations or other Means. Spring3 MVC method is basically independent, the request response data, requests data through parameters, processing results through the MODELMAP to the framework method is not shared between the variables, and Struts2 make is more chaotic, although the method is also independent, But all of its action variables are shared, which does not affect the Program's operation, but it gives us code and trouble reading the Program.

9. in addition, spring3 MVC validation is also a bright spot, support JSR303, processing AJAX Requests is more convenient, just a note @ResponseBody, and then directly return the response Text.


The 18.spring IOC container can help us automate the new object, and we don't have to manually go to the new object after the object is given to the spring tube, which is the transfer of Control.

Spring uses beanfactory to instantiate, configure, and manage objects, but it is just an interface with a Getbean () method.

We generally do not use beanfactory directly, but with its implementation class applicationcontext, this class will automatically parse our configured Applicationcontext.

Spring Dependency Injection:

The IOC is the responsibility of spring to control the life cycle of objects and the relationship between Objects.

Beanfacotry is the simplest container that provides the underlying dependency injection support. ApplicationContext is built on Beanfacotry and provides a system architecture Service.


19.spring does not provide an aop-style journaling system

AOP is the abbreviation of aspect oriented programming, which means: face-cutting programming, through the Pre-compilation method and Run-time dynamic agent implementation of the unified maintenance of the program functions of a Technology. AOP is a continuation of oop, a hotspot in software development, an important content in the spring framework, and a derivative model of functional programming.

With support for aop, Spring implements the logging system with Apache open source components such as LOG4J.

Spring is a collection of a series of lightweight Java EE frameworks. Spring contains an implementation of a "dependency injection" Pattern. Use spring to implement declarative transactions.


20.Servlet is a special Java class that must implement the Servlet interface directly or indirectly.

The servlet client thread invokes the service method to respond to the Client's Request. The servlet interface defines the life cycle approach of the Servlet: init (), service (), Destory () three methods when multiple browser terminals request a Web server, the server initiates a thread for each client, not a process. Import javax.servlet.http.httpservletrequest, You see this package shows that the servlet is a special Java class, Java and javax are Java API packages, Java is the core package, Javax x is the meaning of extension, which is the expansion pack.


One of the features of 21.Spring, simple and powerful transaction management features, including programmatic transactions and declarative Transactions.

1. There are more than 100 APIs involved in transaction management in spring, with only three cores: transactiondefinition, platformtransactionmanager, and Transactionstatus. The so-called transaction management, in fact, is "to follow the given transaction rules to commit or rollback operations." The "given transaction rule" is expressed in transactiondefinition, "by ... To perform a commit or rollback operation "is represented by platformtransactionmanager, and Transactionstatus is used to represent the state of a running Transaction.

2. transactiondefinition, which is described earlier in this interface, is used to define a Transaction. It contains the static properties of a transaction, such as transaction propagation behavior, time-out, and so On. Spring provides us with a default implementation class: defaulttransactiondefinition, which is suitable for most situations. If the class does not meet the requirements, you can implement your own transaction definition by implementing the Transactiondefinition Interface.

3. Platformtransactionmanager is used to perform specific transactional operations.

public interface platformtransactionmanager{

Transactionstatus gettransaction (transactiondefinition Definition) throws transactionexception;

void Commit (transactionstatus Status) throws transactionexception;

void rollback (transactionstatus Status) throws transactionexception;

}

Based on the different persistence APIs or frameworks used at the bottom, Platformtransactionmanager's main implementation classes are as Follows:

Datasourcetransactionmanager: for data persistence using JDBC and Ibatis.

Hibernatetransactionmanager: for data persistence using Hibernate.

Jpatransactionmanager: for data persistence operations using Jpa.

In addition there are jtatransactionmanager, jdotransactionmanager, Jmstransactionmanager and so On.

4. Programmatic transactions require you to join the logic of handling transactions directly in your code, and you may need to explicitly invoke transaction management-related methods such as BeginTransaction (), commit (), rollback () in your code, such as requiring transaction processing when executing a method. You need to open the transaction at the start of the a method, after you have finished processing it. At the end of the method, the transaction is Closed. The practice of declarative transactions is to add annotations to the periphery of the a method or to directly define them in the configuration file, a method requires transactions, and in spring the configuration file is intercepted before and after the A method and the transaction is Added. The difference between the Two. programmatic transactions are more intrusive, but finer in processing Granularity. the equivalent of one is a manual transaction and the other is a system automatic Transaction. A programming transaction is the need to manually write code to commit a transaction, rollback a transaction, and so On. Declarative transactions are defined in the configuration file when a transaction is required, then the system will automatically commit, out of the abnormal automatic rollback, do not need to write commit or rollback in the Code.


Spring transaction:

Spring transactions can be divided into programmatic and declarative transactions.

Spring provides a transactional interface to the Paltformtractionmanager interface, and spring implements different implementations for different transactions.

The greatest advantage of declarative transactions is that you do not need to programmatically manage transactions, so that you do not need to doping transaction-managed code in business logic Code.





This article is from the "11029145" blog, please be sure to keep this source http://11039145.blog.51cto.com/11029145/1885619

The spring knowledge point of Java

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.