I. spring's Core Modules
The Spring framework is a layered architecture consisting of seven well-defined modules. Spring module is built on the core container, which defines the way to create, configure and manage bean s. Each module (or component) that makes up the Spring framework can exist independently or be implemented in conjunction with one or more other modules. The functions of each module are as follows:
1) Spring Core: Core Container, BeanFactory provides component life cycle management, component creation, assembly, destruction and other functions.
SpringContext: Application Context, which extends the core container to provide event handling, internationalization and other functions. It provides some functions of enterprise services and supports JNDI, EJB and RMI.
2) Spring AOP: Providing Face-to-Face Support
3) Spring DAO: Transaction support, JDBC, DAO support
4) Spring ORM: Encapsulation or support for popular O/R Mapping
5) Spring Web: Provide Web application context and provide functional support for Web development, such as requests, forms, exceptions, etc.
6) Spring Web MVC: Full-featured MVC framework, equivalent to Struts.
7) Core container: Core container provides the basic functions of Spring framework. The main component of the core container is BeanFactory, which is the implementation of the factory pattern. BeanFactory uses the Inversion of Control (IOC) pattern to separate application configuration and dependency specifications from the actual application code.
II. The Concept of IOC
Control Inversion (IOC): A design principle in object-oriented programming that reduces the coupling between program codes.
Make the whole program architecture more flexible, and at the same time write the class creation and dependencies in the configuration file, injected by the configuration file, achieve the effect of loose coupling.
At the same time, IOC is also called DI (Dependency Injection), which is a development mode, and Dependency Injection advocates the use of interface programming.
Dependency injection enables components to be developed and then assembled according to dependency relationships between components.
spring injection mode:
(1) Based on specific interfaces (intrusive scheme)
(2) set-based method: The container calls the setter method of the bean after it has been materialized by calling the parametric constructor or the parametric static factory method, which implements setter-based dependency injection.
(3) Constructor-based injection: mainly using constructors and constructors
2.3.Spring container
Spring containers are responsible for generating, assembling, and destroying components, as well as event handling, internationalization and other functions.
(1) BeanFactory<interface>
Core container responsible for component generation and assembly
(2) Implementation mainly includes Xml BeanFactory
(2) ApplicationContext
(3) WebApplicationContext
(4) ……
Resource: interface for packaging resources
xmlBeanFactory: An implementation of BeanFactory that uses Resource objects to find configuration files
BeanFactory.gerBean ("BeanId"): Gets an instance of a Bean named after a parameter or whose Id is equal to the value of the parameter.
BeanFactory (container) returns objects singly by default. The container instantiates an object only when it calls the getBean method.
Spring can be configured with XML or. properties files
(2) Configuration file (XML)
Root elements can have multiple sub-elements, each representing an object to be assembled.
public class HelloServiceTest { @Test public void testHelloWorld() { // 1,Read the configuration file and instantiate one IOC container ApplicationContext context = new ClassPathXmlApplicationContext("helloworld.xml"); // 2,Get it from the container Bean,Notice here that it's entirely "interface-oriented programming, not implementation-oriented" HelloService helloService = context.getBean("helloService", HelloService.class); // 3,Executing business logic helloService.sayHello(); } }
3. Core concepts of AOP
1. Aspect (section)
Aspect is a general term for cross-business logic.
2. Joinpoint
Connection points, which refer to the positions (methods, attributes, etc.) where the cut surface can be woven into the target object.
3. Advice (Notice)
Notification refers to the specific realization of the tangent.
4. Pointcut (entry point)
A pointcut is a rule that notifies which methods or attributes are applied to which classes.
5. Introduction (Introduction)
Introducing means a special notification that dynamically adds methods or attributes to an object.
6. Weaving (weaving)
Weaving means inserting notifications into the target object.
7. Target (target object)
Target object refers to the object that needs to be woven into the tangent.
8. Proxy (Proxy Object)
The proxy object refers to the object formed after the tangent is woven into the target object.
3.1. Principles of AOP
Spring AOP adopts dynamic proxy process:
(1) The facets are dynamically weaved into the target object (the proxy class) by using dynamic proxy to form a proxy object.
(2) If the target object does not implement the proxy interface, Spring will use CGLib to generate the proxy object, which is a subclass of the target object.
(3) If the target object is final class and the proxy interface is not implemented, AOP can not be used.
AOP programming is actually a very simple thing. Throughout AOP programming, programmers only need to participate in three parts:
1. Define common business components
2. Define entry points, one of which may cross-cut multiple business components
3. Define Enhancement Processing. Enhancement Processing is a process action woven into common business components in AOP framework.
So the key to AOP programming is to define entry point and definition enhancement processing. Once appropriate entry point and enhancement processing are defined, AOP framework will automatically generate AOP proxy, that is, the method of proxy object = the method of enhancement processing + the method of proxy object.
A Simple Implementation of AOP Based on Spring
Note that, before explaining, it's pointed out that using Spring AOP, to run the code successfully, it's not enough to use only the jar package Spring provides to developers. Please download two additional jar packages online:
1,aopalliance.jar
2,aspectjweaver.jar
First, define an interface:
public interface HelloWorld { void printHelloWorld(); void doPrint(); }
Define two interface implementation classes:
public class HelloWorldImpl1 implements HelloWorld { public void printHelloWorld() { System.out.println("Enter HelloWorldImpl1.printHelloWorld()"); } public void doPrint() { System.out.println("Enter HelloWorldImpl1.doPrint()"); return ; } }
public class HelloWorldImpl2 implements HelloWorld { public void printHelloWorld() { System.out.println("Enter HelloWorldImpl2.printHelloWorld()"); } public void doPrint() { System.out.println("Enter HelloWorldImpl2.doPrint()"); return ; } }
Cross-cutting concerns, here is the printing time:
public class TimeHandler { public void printTime() { System.out.println("CurrentTime = " + System.currentTimeMillis()); } }
With these three classes, you can implement a simple Spring AOP. Take a look at the configuration of aop.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"> <bean id="helloWorldImpl1" class="com.xrq.aop.HelloWorldImpl1" /> <bean id="helloWorldImpl2" class="com.xrq.aop.HelloWorldImpl2" /> <bean id="timeHandler" class="com.xrq.aop.TimeHandler" /> <aop:config> <aop:aspect id="time" ref="timeHandler"> <aop:pointcut id="addAllMethod" expression="execution(* com.xrq.aop.HelloWorld.*(..))" /><!--First*Represents the return value of a matching arbitrary method, the second*Represents all methods,..The Number of Arbitrary Parameters of Representation Method-->
<aop:before method="printTime" pointcut-ref="addAllMethod" /> <aop:after method="printTime" pointcut-ref="addAllMethod" /> </aop:aspect> </aop:config> </beans>
Call with a main function:
public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("aop.xml"); HelloWorld hw1 = (HelloWorld)ctx.getBean("helloWorldImpl1"); HelloWorld hw2 = (HelloWorld)ctx.getBean("helloWorldImpl2"); hw1.printHelloWorld(); System.out.println(); hw1.doPrint(); System.out.println(); hw2.printHelloWorld(); System.out.println(); hw2.doPrint(); }
The results are as follows:
CurrentTime = 1446129611993 Enter HelloWorldImpl1.printHelloWorld() CurrentTime = 1446129611993 CurrentTime = 1446129611994 Enter HelloWorldImpl1.doPrint() CurrentTime = 1446129611994 CurrentTime = 1446129611994 Enter HelloWorldImpl2.printHelloWorld() CurrentTime = 1446129611994 CurrentTime = 1446129611994 Enter HelloWorldImpl2.doPrint() CurrentTime = 1446129611994
Notes for Spring
Spring's log output relies on commons-logging, but Spring's jar package is not available to us, so we need to download it ourselves.
Spring's main core packages are four [beans, context, core, expression]. A simple spring requires five jar packages. If we want to extend the function, we need to reintroduce the required jar packages in the source libs.
Spring needs to introduce jar packages to connect to databases when connecting to databases, which we need to download separately.
IV. spring MVC
4.1. Spring MVC process
1. The user sends the request to the front-end controller Dispatcher Servlet.
2. Dispatcher Servlet receives a request to call Handler Mapping processor mapper.
3. The processor mapper finds the specific processor (which can be searched according to xml configuration and annotations), generates the processor object and the processor interceptor (if any) and returns them to Dispatcher Servlet.
4. Dispatcher Servlet calls Handler Adapter processor adapter.
5. Handler Adapter calls specific processors (Controller, also known as back-end controllers) through adaptation.
6. The Controller execution completes and returns to Model AndView.
7. Handler Adapter returns the controller execution result Model AndView to Dispatcher Servlet.
8. Dispatcher Servlet passes Model AndView to ViewReslover view parser.
9. ViewReslover parses and returns to the specific View.
10. Dispatcher Servlet renders the view based on View (that is, model data is filled into the view).
11. Dispatcher Servlet responds to users.
4.2. Components:
1. Front-end controller Dispatcher Servlet (no need for engineer development), provided by the framework
Function: Receive requests, respond to results, equivalent to the transponder, central processing unit. The dispatcher servlet reduces the coupling between other components.
The user request arrives at the front-end controller, which is equivalent to c in mvc mode. dispatcher servlet is the center of the whole process control. It calls other components to process the user's request. The existence of dispatcher servlet reduces the coupling between components.
2. Processor mapper Handler Mapping (no need for engineer development), provided by the framework
Role: Find Handler based on the requested url
Handler Mapping is responsible for finding handler or processor according to user's request. Spring MVC provides different mappers to implement different mapping methods, such as configuration file, interface, annotation, etc.
3. Processor adapter Handler Adapter
Function: Execute Handler according to specific rules (rules required by Handler Adapter)
Processors are executed through the Handler Adapter, which is an application of the adapter pattern. More types of processors can be executed by extending the adapter.
4. Processor Handler (Required Engineer Development)
Note: Write Handler according to the requirements of Handler Adapter, so that the adapter can correctly execute Handler.
Handler is the back-end controller following the front-end controller of Dispatcher Servlet. Under the control of Dispatcher Servlet, Handler processes specific user requests.
As Handler involves specific user business requests, engineers are generally required to develop Handler according to business requirements.
5. View resolver (no need for engineer development), provided by framework
Function: View parsing, parsing into a real view based on the logical view name
View Resolver is responsible for generating View view from processing results. View Resolver first parses the logical view name into physical view name, that is, specific page address, and regenerates the View view object. Finally, View is rendered to display the processing results to users through the page. The spring MVC framework provides many types of view views, including jstlView, freemarkerView, pdfView, etc.
Generally, the model data need to be displayed to users through page label or page template technology. Engineers need to develop specific pages according to business needs.
6. View View (requires engineers to develop jsp...)
View is an interface that implements classes that support different View types (jsp, freemarker, pdf...)
4.3. Spring MVC-mvc.xml Profile Fragment Explanation
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- Package name for automatic scanning --> <context:component-scan base-package="com.app,com.core,JUnit4" ></context:component-scan> <!-- Default annotation mapping support --> <mvc:annotation-driven /> <!-- View Interpretation Class --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/><!--May be empty,Easy to implement your own logic of selecting View interpretation classes based on extensions --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> <!-- Interceptor --> <mvc:interceptors> <bean class="com.core.mvc.MyInteceptor" /> </mvc:interceptors> <!-- Access Scheme 1 for Static Resource Files (Option 2) --> <mvc:default-servlet-handler/> <!-- Access Scheme 2 for Static Resource Files (Option 2)--> <mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/> <mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/> <mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/> </beans>
<context: component-scan/> scans annotations on classes in specified packages. Commonly used annotations are:
@ Controller Declares Action Components
@ Service: Declare Service Component @Service("myMovieLister")
@ Repository declares the Dao component
@ Component refers to a component in general, when it is not easy to categorize.
@ Request Mapping ("/menu") Request Mapping
@ Resource is used for injection, (provided by j2ee) is assembled by name by default, @Resource (name= "bean Name")
@ Autowired is used for injection, (provided by srping) default type-by-type assembly
@ Transactional (rollbackFor={Exception.class}) transaction management
@ResponseBody
@ Scope("prototype") sets the scope of the bean
@ Running process of Model Atrribute
1. Execution of @Model Atrribute annotation modification: Extract the object from the database and place the object in the Map with the key user
2. Spring MVC fetches User objects from the Map collection and assigns the request parameters of the form to the corresponding attributes of the user object.
3. Spring MVC passes the above objects into the parameters of the target method
4. This user object exists in the request, and if there are corresponding fields in the jsp form, the form will be filled automatically.
Note: In the @Model Atrribute decorated method, the key to place a Map should be the same as the parameter name of the target method.
4.4.Converter and Formatter
Spring's Converter can convert one type into another.
In use, you must write a java class that implements the org. spring framework. core. convert. converter. Converter interface. The declaration of this interface is as follows
public interface Converter<S, T> { T convert(S var1); }
Here S denotes the source type and T denotes the target type.
Here's a Converter that converts String type to Date type
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.convert.converter.Converter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class StringToDateConverter implements Converter<String, Date>{ private static final Log logger = LogFactory.getLog(StringToDateConverter.class); private String datePattern; public StringToDateConverter(String datePattern) { this.datePattern = datePattern; } public Date convert(String s) { try { SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern); dateFormat.setLenient(false); return dateFormat.parse(s); } catch (ParseException e) { throw new IllegalArgumentException("invalid date format. Please use this pattern\"" + datePattern + "\""); } } }
To use Spring MVC application customized Converter, you need to add a conversionService bean to the configuration file. The class name of the bean must be org. springframework. context. support. ConversionService FactoryBean. This bean must contain a converters attribute that lists all custom Converters to be used in the application. The following bean declaration registers the StringToDateConverter above.
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="app06a.converter.StringToDateConverter"> <constructor-arg name="datePattern" value="yyyy-MM-dd"/> </bean> </set> </property> </bean>
After that, you also need to assign the bean name to the conversion-service attribute of the annotation-drive element, as follows
<mvc:annotation-driven conversion-service="conversionService"/>
2Formatter
Formatter and Converter In the same way, one type is transformed into another. However, Formatter The source type must be one String.
When used, an implementation must be written org.springframework.format.Formatter Interface java Class. The declaration of this interface is as followspublic interface Formatter<T> extends Printer<T>, Parser<T> { } public interface Printer<T> { String print(T var1, Locale var2); } public interface Parser<T> { T parse(String var1, Locale var2) throws ParseException; }
Here T represents the target type to be converted by the input string.
The parse method parses a String into a target type using the specified Locale. The print method, on the contrary, is a string representation that returns the target object.
The following shows a Formatter that converts String type to Date type
import org.springframework.format.Formatter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class DateFormatter implements Formatter<Date>{ private String datePattern; private SimpleDateFormat dateFormat; public DateFormatter(String datePattern) { this.dateFormat = dateFormat; dateFormat = new SimpleDateFormat(datePattern); dateFormat.setLenient(false); } public Date parse(String s, Locale locale) throws ParseException { try { SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern); dateFormat.setLenient(false); return dateFormat.parse(s); } catch (ParseException e) { throw new IllegalArgumentException("invalid date format. Please use this pattern\"" + datePattern + "\""); } } public String print(Date date, Locale locale) { return dateFormat.format(date); } }
To use Spring MVC application customized Formatter, you need to add a conversionService bean to the configuration file. The class name of the bean must be org. springframework. format. support. FormattingConversionService FactoryBean. The bean can register Formatter with a formatters attribute and Converter with a converters attribute. The following bean declaration registers the above DateFormatter.
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="formatters"> <set> <bean class="app06a.formatter.DateFormatter"> <constructor-arg name="datePattern" value="yyyy-MM-dd"/> </bean> </set> </property> </bean>
After that, you also need to assign the bean name to the conversion-service attribute of the annotation-drive element, as follows
<mvc:annotation-driven conversion-service="conversionService"/>
3. Choose Converter or Formatter
Converter is a general tool that converts one type to another. For example, convert String to Date, or Long to Date. Converter can be used in both the web layer and other layers.
Formatter can only convert String to another java type. For example, String is converted to Date, but it cannot convert Long to Date. Therefore, Formatter applies to the web tier. For this reason, in Spring MVC applications, it is more appropriate to choose Formatter than Converter.
4.5.Validator
Adding constraints to JavaBean s to be validated
Add @Valid before the controller parameters to be validated
4.6. Advantages of Springmvc
1. It is based on component technology. All application objects, whether controllers and views, or business objects, are java components. They are closely integrated with other infrastructure provided by Spring.
2. Not dependent on the Servlet API (although the goal is so, it does depend on the Servlet when it is implemented)
3. You can use any view technology, not just JSP.
4. Mapping strategies to support various request resources
5. It should be easy to expand.