Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Build a micro-service framework and test environment-11-Spring Framework

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

I. Architecture and component diagrams

The architecture of Spring 5 is as follows:

The dependency graph between the components is as follows:

Spring5 has 20 components (more than 1300 files), which are integrated in the core container (Core Container), AOP (Aspect Oriented Programming) and device support (Instrmentation), data access and integration (Data Access/Integeration), Web, message transmission (Messaging), and Test.

1. Core container

It is composed of spring-beans, spring-core, spring-context and spring-expression (Spring Expression Language, SpEL), with four components.

The spring-beans and spring-core modules are the core modules of the Spring framework, including Inversion of

Control, IOC) and dependency injection (Dependency Injection, DI)

Among them, the BeanFactory interface is the core interface in the Spring framework, which is the concrete implementation of the factory pattern. BeanFactory uses control inversion to separate the application's configuration and dependency specifications from the actual application code. However, the BeanFactory container does not instantiate the Bean automatically after instantiation, and the BeanFactory container assembles the instantiation and dependency of the Bean only when the Bean is used.

The spring-context module is built on top of the core module. He extends BeanFactory and adds functions such as Bean lifecycle control, framework event architecture and resource loading transparency for her. In addition, this module also provides a lot of enterprise-level support, such as mail access, remote access, task scheduling and so on. ApplicationContext is the core interface of this module, and it is the superclass of BeanFactory. Unlike BeanFactory, ApplicationContext container instantiates all single-instance Bean automatically instantiates and assembles dependencies, making it in a standby state.

Spring-expression module is an extension module of Unified expression language (EL), which can query and manage running objects.

At the same time, it is also convenient to call object methods, operation arrays, collections, and so on. Its syntax is similar to that of traditional EL, but provides additional functions, the best of which are function calls and template functions for simple strings. The features of this language are based on the requirements of Spring products, and it can easily interact with Spring IOC.

2. AOP and device support

It is composed of spring-aop, spring-aspects and spring-instrument, with three components.

Spring-aop is another core module of Spring and the main implementation module of AOP. As one of the programming ideas that have the greatest influence on programmers after OOP, AOP has greatly expanded people's thinking on programming. In Spring, he is based on the dynamic proxy technology of JVM, and then designs a series of AOP crosscutting implementations, such as pre-notification, return notification, exception notification and so on. At the same time, the Pointcut interface matches the pointcut, which can use the existing pointcut to design the crosscutting, or expand the relevant methods to cut in according to the needs.

The spring-aspects module is integrated from the AspectJ framework, mainly to provide a variety of AOP implementation methods for Spring AOP.

The spring-instrument module is designed based on the "ava.lang.instrument" in JAVA SE, which should be regarded as

A supporting module of AOP, the main function is to generate a proxy class when JVM is enabled. Programmers modify the bytes of the class at run time through the proxy class, thus changing the function of a class and realizing the function of AOP.

3. Data access and integration

It is composed of spring-jdbc, spring-tx, spring-orm, spring-jms and spring-oxm, and has five components.

The spring-jdbc module is the main implementation module of the JDBC abstract framework provided by Spring, which is used to simplify Spring JDBC. It mainly provides JDBC template mode, relational database object mode, SimpleJdbc mode and transaction management to simplify JDBC programming. The main implementation classes are JdbcTemplate, SimpleJdbcTemplate and NamedParameterJdbcTemplate.

Spring-tx module is the implementation module of Spring JDBC transaction control. Using Spring framework, it encapsulates transactions well, and can be flexibly configured at any layer through its AOP configuration; but in many requirements and applications, directly using JDBC transaction control still has its advantages. In fact, transactions are based on business logic; a complete business should correspond to a method in the business layer; if the business operation fails, the whole transaction should be rolled back; therefore, transaction control should definitely be placed in the business layer; however, the design of the persistence layer should follow a very important principle: to ensure the atomicity of the operation, that is, every method in the persistence layer should be indivisible. Therefore, when using Spring JDBC transaction control, you should pay attention to its particularity.

Spring-orm module is the supporting module of ORM framework, which mainly integrates Hibernate, Java Persistence API (JPA) and Java Data Objects (JDO) for resource management, data access object (DAO) implementation and transaction strategy.

The spring-jms module (Java Messaging Service) can send and receive messages from Spring Framework 4.1,

Later, he also provided support for the spring-messaging module.

The spring-oxm module mainly provides an abstraction layer to support OXM (OXM is the abbreviation of Object-to-XML-Mapping, which is an O/M-mapper that maps java objects to XML data, or XML data to java objects), such as JAXB,Castor, XMLBeans, JiBX and XStream.

4 、 Web

It is composed of spring-web, spring-webmvc, spring-websocket and spring-webflux, and has four components.

The spring-web module provides the most basic Web support for Spring, which is mainly based on the core container, initializes the IOC container through Servlet or Listeners, and also includes some Web-related support.

Spring-webmvc module is a Web-Servlet module, which implements the Web application of Spring MVC (model-view-Controller).

The spring-websocket module is mainly a protocol for full-duplex communication with the front end of Web.

Spring-webflux is a new non-blocking functional Reactive Web framework that can be used to build asynchronous, non-blocking, event-driven services with good scalability.

5. Message transmission

Including spring-messaging, 1 component.

Spring-messaging is a new module added from Spring4, and its main responsibility is to integrate some basic messaging applications for the Spring framework.

6 、 Test

Contains spring-test,1 components.

The spring-test module mainly provides support for testing, after all, it is very important for any enterprise to be able to perform some integration tests or other tests without publishing to your application server or connecting to other enterprise facilities.

II. Spring Bean Foundation

The Bean configuration information defines the implementation and dependency of Bean. According to various forms of Bean configuration information, the Spring container establishes the Bean definition registry inside the container, then loads and instantiates the Bean according to the registry, and establishes the dependency relationship between Bean and Bean. Finally, these ready Bean are put into the Bean cache pool for outer applications to call. The following picture is an old picture:

1. Bean configuration

There are three ways to configure bean:

Configure Bean based on xml

Define Bean using annotations

Provide Bean definition information based on java class

1.1 configure Bean based on xml

For XML-based configurations, Spring 2.0 uses the Schema format later, so that different types of configurations have their own namespaces, which makes the configuration files more extensible.

① default namespace: it has no space name and is used for the definition of Spring Bean

② xsi namespace: this namespace is used to specify the corresponding Schema style file for the namespace in each document. It is a standard namespace defined by the standards organization.

③ aop Namespace: this namespace is the namespace of the Spring configuration AOP and is a user-defined namespace.

The definition of a namespace is divided into two steps: the first step is to specify the name of the namespace; the second step is to specify the location of the Schema document style file for the namespace, separated by spaces or carriage feed.

1.1.1 basic Bean configuration

The configuration snippet that defines a brief Bean in the configuration file of the Spring container is as follows:

In general, a Bean in the Spring IOC container is one of the corresponding configuration files, and this image correspondence should be easy to understand. Id is the name of the Bean, and the corresponding Bean can be obtained through the container's getBean ("foo"). It plays the role of location and search in the container, and is the bridge between the external program and the Spring IOC container. The class attribute specifies the implementation class corresponding to Bean.

The following is a XML-based configuration file that defines two simple Bean:

1.1.2 dependency injection

Attribute injection

Constructor injection

Factory injection

1.2 define Bean using annotations

We know that the three main requirements for the successful startup of the Spring container are: the Bean definition information, the Bean implementation class, and the Spring itself. If the XML-based configuration is adopted, the Bean definition information is separated from the Bean implementation class itself, while when the annotation-based configuration is adopted, the Bean definition information is realized by annotating the Bean implementation class.

The following is a Bean that defines a DAO using annotations:

Package com.baobaotao.anno

Import org.springframework.stereotype.Component

Import org.springframework.stereotype.Repository

/ / ① defines a Bean of DAO through Repository

@ Component ("userDao")

Public class UserDao {

}

At ①, we use the @ Component annotation to annotate the class at the UserDao class declaration, which is recognized by the Spring container, which automatically converts POJO to container-managed Bean.

It is equivalent to the following XML configuration:

In addition to @ Component, Spring provides three functional basic and @ Component equivalent annotations, which are used to annotate Controller in DAO, Service, and Web layers, respectively, so they are also called derivative annotations of Bean: (similar to defining Bean in the xml file

@ Repository: used to annotate DAO implementation classes

@ Service: used to annotate Service implementation classes

@ Controller: used to annotate Controller implementation classes

The reason for providing these three special annotations outside @ Component is to clarify the purpose of the annotation class itself, and Spring will give them some special functionality.

1.2.1 start the spring container with annotated configuration information

Spring provides a context namespace, which provides a way to apply annotations to define Bean by scanning class packages:

Declare the context namespace at ①, and specify a base class package that needs to be scanned through the component-scan base-package attribute of the context namespace at ②. The Spring container will scan all classes in this base class package and obtain the definition information of Bean from the class annotation information.

If you want to scan only specific classes instead of all the classes under the base package, you can use the resource-pattern attribute to filter specific classes, as follows:

Here we set the base class package to com.baobaotao, and by default the value of the resource-pattern attribute is "* * / * .class", that is, all classes in the base class package. If we set it to "anno/*.class" here, Spring will scan only the classes in the anno subpackage in the base package.

1.3 provide Bean definitions based on java classes

In a normal POJO class, you can provide the spring container with Bean definition information as long as you mark the @ Configuration annotation, and each class method marked with @ Bean is equivalent to providing a Bean definition information.

Package com.baobaotao.conf

Import org.springframework.context.annotation.Bean

Import org.springframework.context.annotation.Configuration

/ / ① marks a POJO as a configuration class that defines Bean

@ Configuration

Public class AppConf {

/ / ② the following two methods define two Bean to provide the instantiation logic of Bean

@ Bean

Public UserDao userDao () {

Return new UserDao ()

}

@ Bean

Public LogDao logDao () {

Return new LogDao ()

}

/ / ③ defines the Bean of logonService

@ Bean

Public LogonService logonService () {

LogonService logonService = new LogonService ()

/ / ④ injects the Bean defined at ② and ③ into LogonService Bean

LogonService.setLogDao (logDao ())

LogonService.setUserDao (userDao ())

Return logonService

}

}

① marks the @ Configuration annotation at the definition of the APPConf class, indicating that this class can be used to provide Bean definition information for Spring. The @ Bean annotation can be marked at the method of the class. The type of Bean is determined by the type of value returned by the method. The name is the same as the method name by default, or you can specify the Bean name by displaying the input parameter, such as @ Bean (name= "userDao"). The instantiation logic of Bean is provided directly in the methods annotated by @ Bean.

The userDao () and logDao () methods at ② define a Bean for UserDao and a LogDao, and their Bean names are userDao and logDao, respectively. At ③, another logonService Bean is defined, and two Bean defined at ② premises are injected at ④.

Therefore, the above configuration is equivalent to the following XML configuration:

Compared with XML-based or annotation-based configuration, the former implements the instantiation of Bean and the assembly between Bean more flexibly through code, but the latter two are declared by configuration, which are slightly less flexible in terms of flexibility, but simpler in configuration.

2 Bean injection

There are two ways to inject Bean, one is to configure it in XML, where there are attribute injection, constructor injection, and factory method injection, respectively, and the other is to inject @ Autowired,@Resource,@Required using annotations.

2.1 configure dependency injection in the xml file

2.1.1 attribute injection

Attribute injection is to inject the attribute value or dependent object of Bean through the setXxx () method. Because the attribute injection method has the advantages of high selectivity and flexibility, attribute injection is the most common injection method in practical applications.

Property injection requires Bean to provide a default constructor and a corresponding Setter method for the properties that need to be injected. Spring first calls the default constructor of Bean to instantiate the Bean object, and then calls the Setter method to inject the property value through reflection.

Package com.baobaotao.anno

Import org.springframework.beans.factory.BeanNameAware

Public class LogonService implements BeanNameAware {

Private LogDao logDao

Private UserDao userDao

Public void setUserDao (UserDao userDao) {

This.userDao = userDao

}

Public void setLogDao (LogDao logDao) {

This.logDao = logDao

}

Public LogDao getLogDao () {

Return logDao

}

Public UserDao getUserDao () {

Return userDao

}

Public void setBeanName (String beanName) {

System.out.println ("beanName:" + beanName)

}

Public void initMethod1 () {

System.out.println ("initMethod1")

}

Public void initMethod2 () {

System.out.println ("initMethod2")

}

}

Bean.xml configuration:

2.1.2 Construction method injection

The premise of using constructor injection is that Bean must provide a constructor with parameters. For example:

Package com.baobaotao.anno

Import org.springframework.beans.factory.BeanNameAware

Public class LogonService implements BeanNameAware {

Public LogonService () {}

Public LogonService (LogDao logDao, UserDao userDao) {

This.logDao = logDao

This.userDao = userDao

}

Private LogDao logDao

Private UserDao userDao

Public void setUserDao (UserDao userDao) {

This.userDao = userDao

}

Public void setLogDao (LogDao logDao) {

This.logDao = logDao

}

Public LogDao getLogDao () {

Return logDao

}

Public UserDao getUserDao () {

Return userDao

}

Public void setBeanName (String beanName) {

System.out.println ("beanName:" + beanName)

}

Public void initMethod1 () {

System.out.println ("initMethod1")

}

Public void initMethod2 () {

System.out.println ("initMethod2")

}

}

Bean.xml configuration:

2.1.3 Factory method injection

Non-static factory method:

Some factory methods are non-static, that is, you must instantiate the factory class before you can call the factory method.

Package com.baobaotao.ditype

Public class CarFactory {

Public Car createHongQiCar () {

Car car = new Car ()

Car.setBrand ("Red Flag CA72")

Return car

}

Public static Car createCar () {

Car car = new Car ()

Return car

}

}

The factory class is responsible for creating one or more instances of the target class. Factory class methods generally return instances of the target class in the form of interfaces or abstract class variables. The factory class shields the instantiation steps of the target class from the outside. The caller does not even know what the specific target class is.

Static factory method:

Many factory classes are static, which means that users can call factory class methods without creating an instance of the factory class, so static factory methods are more convenient than non-static factory methods.

2.2 injection using annotations

2.2.1 automatic injection using @ Autowired

Spring implements Bean dependency injection through the @ Autowired annotation. Here is an example:

Package com.baobaotao.anno

Import org.springframework.beans.factory.BeanNameAware

Import org.springframework.beans.factory.annotation.Autowired

Import org.springframework.beans.factory.annotation.Qualifier

Import org.springframework.stereotype.Service

/ / ① defines a Bean of Service (there is no need to define Bean in XML)

@ Service

Public class LogonService implements BeanNameAware {

/ / ② injects Bean of LogDao and UserDao respectively (there is no need to define property attribute injection in XML)

@ Autowired (required=false)

Private LogDao logDao

@ Autowired

@ Qualifier ("userDao")

Private UserDao userDao

Public LogDao getLogDao () {

Return logDao

}

Public UserDao getUserDao () {

Return userDao

}

Public void setBeanName (String beanName) {

System.out.println ("beanName:" + beanName)

}

Public void initMethod1 () {

System.out.println ("initMethod1")

}

Public void initMethod2 () {

System.out.println ("initMethod2")

}

}

At ①, we use @ Service to label LogonService as a Bean, and at ②, we inject LogDao and UserDao's Bean through @ Autowired. By default, @ Autowired looks for a matching Bean in the container by type matching, and when there is one or only one matching Bean, Spring injects it into the variable annotated by @ Autowired.

2.2.2 use the required attribute of @ Autowired

If there is no Bean,Spring container in the container that matches the type of dimension variable, it will report an exception of NoSuchBeanDefinitionException when it starts. If you want Spring not to throw an exception even if it cannot find a matching Bean to complete the injection, you can use @ Autowired (required=false) to mark it:

@ Service

Public class LogonService implements BeanNameAware {

@ Autowired (required=false)

Private LogDao logDao

...

}

By default, the value of the required attribute of @ Autowired is true, which requires that a matching Bean must be found, or an exception will be reported.

2.2.3 use @ Qualifier to specify the name of the injected Bean

If there is more than one matching Bean in the container, you can qualify the name of the Bean with the @ Qualifier annotation, as shown below:

@ Service

Public class LogonService implements BeanNameAware {

@ Autowired (required=false)

Private LogDao logDao

/ / ① injects Bean named UserDao and type UserDao

@ Autowired

@ Qualifier ("userDao")

Private UserDao userDao

}

Assuming that the container has two Bean of type UserDao, one named userDao and the other named otherUserDao, a Bean named userDao is injected at the ①.

2.2.4 annotating class methods

@ Autowired can mark the variables of class members and the input parameters of methods. Let's annotate the methods of the class with @ Autowired:

Package com.baobaotao.anno

Import org.springframework.beans.factory.BeanNameAware

Import org.springframework.beans.factory.annotation.Autowired

Import org.springframework.beans.factory.annotation.Qualifier

Import org.springframework.stereotype.Service

@ Service

Public class LogonService implements BeanNameAware {

Private LogDao logDao

Private UserDao userDao

@ Autowired

Public void setLogDao (LogDao logDao) {

This.logDao = logDao

}

@ Autowired

@ Qualifier ("userDao")

Public void setUserDao (UserDao userDao) {

System.out.println ("auto inject")

This.userDao = userDao

}

}

If a method has more than one input parameter, by default, Spring automatically selects a Bean that matches the type of input parameter for injection. Spring allows you to label the method input parameter @ Qualifier to specify the name of the injected Bean, as shown below:

@ Autowired

Public void init (@ Qualifier ("userDao") UserDao userDao,LogDao logDao) {

System.out.println ("multi param inject")

This.userDao = userDao

This.logDao = logDao

}

In the above example, the input parameter of UserDao injects a Bean named userDao, while the input parameter of LogDao injects Bean of type LogDao.

In general, most of the Bean in the Spring container is a single instance, so we generally do not need to specify a name for the Bean through the value attribute of @ Repository, @ Service and other annotations, nor do we need to use @ Qualifier to inject by name.

2.2.5 support for standard notes

In addition, Spring also supports @ Resource and @ Inject annotations, which are similar to @ Autowired annotations in that they provide automatic injection of class variables and method input parameters. @ Resource requires an attribute with the Bean name, and if the property is empty, the variable or method name at the label is automatically taken as the name of the Bean.

Package com.baobaotao.anno

Import javax.annotation.PostConstruct

Import javax.annotation.PreDestroy

Import javax.annotation.Resource

Import org.springframework.stereotype.Component

@ Component

Public class Boss {

Private Car car

Public Boss () {

System.out.println ("construct...")

}

/ / @ Autowired

/ / private void setCar (Car car) {

/ / System.out.println ("execute in setCar")

/ / this.car = car

/ /}

@ Resource ("car")

Private void setCar (Car car) {

System.out.println ("execute in setCar")

This.car = car

}

@ PostConstruct

Private void init1 () {

System.out.println ("execute in init1")

}

@ PostConstruct

Private void init2 () {

System.out.println ("execute in init1")

}

@ PreDestroy

Private void destory1 () {

System.out.println ("execute in destory1")

}

@ PreDestroy

Private void destory2 () {

System.out.println ("execute in destory2")

}

}

At this point, if @ Resource does not specify the "car" attribute, you can also get the Bean name that needs to be injected based on the property method. It can be seen that @ Autowired injects Bean,@Resource by type matching by default and injects Bean by name matching. @ Inject, like @ Autowired, is injected Bean by type matching, except that it does not have a required attribute. It can be seen that neither @ Resource nor @ Inject annotations are as functional as @ Autowired, so you don't have to worry about them unless you have to. (similar to using or injecting in Xml, if @ Autowired or Resource and so on are used, there is no need to use attribute injection and constructor injection when defining Bean.)

2.2.6 about Autowired and @ Resource

1.@Autowired injection is injected by type, and injection is fine as long as the bean type in the configuration file is the same as the required bean type. However, if there is more than one bean of the same type, there will be a problem with the injection and the Spring container cannot be started.

The 2.@Resourced tag is injected according to the name of bean. If we do not specify the name of bean when using @ Resource, and there is no bean with that name in the Spring container, @ Resource will be degenerated to @ Autowired, that is, injected by type, which may violate the original intention of using @ Resource. Therefore, it is recommended that you specify the name @ Resource (name= "xxx") of bean when using @ Resource.

2.2.7 several ways to make @ Resource and @ Autowired effective

1. Explicitly specify in the xml configuration file

two。 Using context:annotation-config in xml configuration files

3. Using context:component-scan in xml configuration files

4. Override the Context of the Spring container and call AnnotationConfigUtils.registerAnnotationConfigProcessors () when customizing the BeanFactory to add the two annotation handlers to the container.

Write your own XmlWebApplicationContext, override customizeBeanFactory () in this context, and call the AnnotationConfigUtils.registerAnnotationConfigProcessors () method in this method to add these two automatic annotation processors to the BeanDefinitions, so that @ Resource and @ Autowired are automatically injected in the public web layer. As follows:

Package com.alibaba.citrus.springext.support.context

Import com.alibaba.citrus.springext.ResourceLoadingExtendable

Import com.alibaba.citrus.springext.ResourceLoadingExtender

Import com.alibaba.citrus.springext.support.context.InheritableListableBeanFactory

Import com.alibaba.citrus.springext.support.resolver.XmlBeanDefinitionReaderProcessor

Import java.io.IOException

Import org.springframework.beans.factory.support.DefaultListableBeanFactory

Import org.springframework.beans.factory.xml.XmlBeanDefinitionReader

Import org.springframework.context.ApplicationListener

Import org.springframework.context.annotation.AnnotationConfigUtils

Import org.springframework.core.io.Resource

Import org.springframework.core.io.support.ResourcePatternResolver

Public class XmlWebApplicationContext extends org.springframework.web.context.support.XmlWebApplicationContext implements ResourceLoadingExtendable {

Private ResourceLoadingExtender resourceLoadingExtender

Private boolean parentResolvableDependenciesAccessible = true

Public XmlWebApplicationContext () {

}

Public boolean isParentResolvableDependenciesAccessible () {

Return this.parentResolvableDependenciesAccessible

}

Public void setParentResolvableDependenciesAccessible (boolean parentResolvableDependenciesAccessible) {

This.parentResolvableDependenciesAccessible = parentResolvableDependenciesAccessible

}

Public void setResourceLoadingExtender (ResourceLoadingExtender resourceLoadingExtender) {

If (this.resourceLoadingExtender! = null) {

This.getApplicationListeners () remove (this.resourceLoadingExtender)

}

This.resourceLoadingExtender = resourceLoadingExtender

If (resourceLoadingExtender instanceof ApplicationListener) {

This.addApplicationListener ((ApplicationListener) resourceLoadingExtender)

}

}

Protected void initBeanDefinitionReader (XmlBeanDefinitionReader beanDefinitionReader) {

(new XmlBeanDefinitionReaderProcessor (beanDefinitionReader)) .addConfigurationPointsSupport ()

}

Protected void customizeBeanFactory (DefaultListableBeanFactory beanFactory) {

Super.customizeBeanFactory (beanFactory)

/ / AnnotationConfigUtils.registerAnnotationConfigProcessors () method adds these two automatic annotation processors to BeanDefinitions, and supports @ Resource and @ Autowired automatic injection at the web layer.

AnnotationConfigUtils.registerAnnotationConfigProcessors (beanFactory, (Object) null)

}

Protected DefaultListableBeanFactory createBeanFactory () {

Return (DefaultListableBeanFactory) (this.isParentResolvableDependenciesAccessible ()? new InheritableListableBeanFactory (this.getInternalParentBeanFactory ()): super.createBeanFactory ())

}

Protected Resource getResourceByPath (String path) {

Resource resource = null

If (this.resourceLoadingExtender! = null) {

Resource = this.resourceLoadingExtender.getResourceByPath (path)

}

If (resource = = null) {

Resource = super.getResourceByPath (path)

}

Return resource

}

Protected ResourcePatternResolver getResourcePatternResolver () {

Final ResourcePatternResolver defaultResolver = super.getResourcePatternResolver ()

Return new ResourcePatternResolver () {

Public Resource [] getResources (String locationPattern) throws IOException {

ResourcePatternResolver resolver = null

If (XmlWebApplicationContext.this.resourceLoadingExtender! = null) {

Resolver = XmlWebApplicationContext.this.resourceLoadingExtender.getResourcePatternResolver ()

}

If (resolver = = null) {

Resolver = defaultResolver

}

Return resolver.getResources (locationPattern)

}

Public ClassLoader getClassLoader () {

Return defaultResolver.getClassLoader ()

}

Public Resource getResource (String location) {

Return defaultResolver.getResource (location)

}

}

}

}

3. × × ×

1. Cloning

Git clone https://github.com/spring-projects/spring-framework.git

2. Use maven

(1) Core

Dependency injection, events, resources, i18n, validation, data binding, type conversion, SpEL, AOP are supported, depending on:

Org.springframework

Spring-core

5.1.2.RELEASE

(2) WebMVC

Support MVC, View Technologies, CORS, Web Socket, RESTful, and inherit Spring Web functions core HTTP integration, including Servlet filters, Spring HTTP Invoker, infrastructure to integrate with

Other web frameworks and HTTP technologies e.g. Hessian, Burlap . Its dependencies are:

Org.springframework

Spring-webmvc

5.1.2.RELEASE

Note: if you rely on spring-webmvc, you don't need to rely on spring-web.

(3) spring-boot-starter-web

Note: initiator spring-boot-starter-web builds RESTful-style web applications based on Spring MVC, using embedded tomcat as the default container

3. Use Gradle

(1) spring-core and spring-webmvc

Dependencies {

Api 'org.springframework:spring-core:5.0.8.RELEASE'

Api 'org.springframework:spring-webmvc:5.0.8.RELEASE'

}

Or

Dependencies {

Compile group: 'org.springframework', name:' spring-core', version: '5.0.8.RELEASE'

Compile group: 'org.springframework', name:' spring-webmvc', version: '5.0.8.RELEASE'

}

(2) spring-boot-starter-web

Dependencies {

Compile ("org.springframework.boot:spring-boot-starter-web")

}

Note: initiator spring-boot-starter-web builds RESTful-style web applications based on Spring MVC, using embedded tomcat as the default container

You can learn about annotations and initiator lists in "Spring Boot".

IV. SOAP Web Service production service

(1) rely on Spring Web

* Maven***

Org.springframework.boot

Spring-boot-starter-web-services

* Gradle***

Dependencies {

Compile ("org.springframework.boot:spring-boot-starter-web-services")

}

(2) define web service domain

Use XSD (XML schema file) to define the Domain.

For example, create a countries.xsd file under the resources directory to define the name, population, capital, and currency of the country.

(3) generate Domain class

Domain classes are automatically created by maven or gradle based on the xsd file.

* * Maven*** modifies pom.xml

First, add dependencies:

Wsdl4j

Wsdl4j

Then add the build plug-in:

Org.codehaus.mojo

Jaxb2-maven-plugin

1.6

Xjc

Xjc

${project.basedir} / src/main/resources/

${project.basedir} / src/main/java

False

Notice that the plugin tag is placed inside the plugins tag.

After saving, eclipse automatically executes xjc and automatically generates six java files in the java directory:

* Gradle*** needs to configure JAXB in build.gradle:

A. Add: in bootJar:

From genJaxb.classesDir

B. Add configurations:

Configurations {

Jaxb

}

C. Add dependence on Spring WS and JAXB in dependencies:

Compile ("wsdl4j:wsdl4j:1.6.1")

Jaxb ("org.glassfish.jaxb:jaxb-xjc:2.2.11")

Compile (files (genJaxb.classesDir) .builtBy (genJaxb))

D. Add genJaxb task (Ant task, because gradle does not support JAXB task):

Task genJaxb {

Ext.sourcesDir = "${buildDir} / generated-sources/jaxb"

Ext.classesDir = "${buildDir} / classes/jaxb"

Ext.schema = "src/main/resources/countries.xsd"

Outputs.dir classesDir

DoLast () {

Project.ant {

Taskdef name: "xjc", classname: "com.sun.tools.xjc.XJCTask"

Classpath: configurations.jaxb.asPath

Mkdir (dir: sourcesDir)

Mkdir (dir: classesDir)

Xjc (destdir: sourcesDir, schema: schema) {

Arg (value: "- wsdl")

Produces (dir: sourcesDir, includes: "* * / * .java")

}

Javac (destdir: classesDir, source: 1.6, target: 1.6, debug: true

DebugLevel: "lines,vars,source"

Classpath: configurations.jaxb.asPath) {

Src (path: sourcesDir)

Include (name: "* * / * .java")

Include (name: "* .java")

}

Copy (todir: classesDir) {

Fileset (dir: sourcesDir, erroronmissingdir: false) {

Exclude (name: "* * / * .java")

}

}

}

}

}

E. Add afterEclipseImport tasks

Task afterEclipseImport {

DependsOn "genJaxb"

}

The java class is automatically generated after saving. Note that gradle uses the ant task, which is much more complex than maven.

For more information about jaxb and ant tasks, see "9, JAXB, and ANT."

(4) create Repository class

This class requires the annotation @ Component to provide data to web service.

For example:

Create the CountryRepository class and add the annotation @ Component

B. add a static member:

Private static final Map countries = new HashMap ()

C. Add the method initData to initialize the data. The return type is void, and the code is:

Country spain = new Country ()

Spain.setName ("Spain")

Spain.setCapital ("Madrid")

Spain.setCurrency (Currency.EUR)

Spain.setPopulation (46704314)

Countries.put (spain.getName (), spain)

Country poland = new Country ()

Poland.setName ("Poland")

Poland.setCapital ("Warsaw")

Poland.setCurrency (Currency.PLN)

Poland.setPopulation (38186860)

Countries.put (poland.getName (), poland)

Country uk = new Country ()

Uk.setName ("United Kingdom")

Uk.setCapital ("London")

Uk.setCurrency (Currency.GBP)

Uk.setPopulation (63705000)

Countries.put (uk.getName (), uk)

D. Add the search method findCountry. The parameter is name and Country is returned.

Assert.notNull (name, "The country's name must not be null")

Return countries.get (name)

(5) create a service endpoint to process SOAP requests

Create the endpoint class, annotate @ Endpoint, add the constructor and annotate @ Autowired:

Follow the country example:

@ Autowired

Public CountryEndpoint (CountryRepository countryRepository) {

This.countryRepository = countryRepository

}

Where @ Endpoint registers a Spring WS class as a candidate for processing SOAP messages.

B. Add static member NAMESPACE_URI

For example:

Private static final String NAMESPACE_URI = "http://jiaxiaomei.com/test/soap-test";

C. Increase the private members of Repository

For example:

Private CountryRepository countryRepository

D. Add query methods and annotate @ PayloadRoot, @ RequestPayload and @ ResponsePayload

For example:

@ PayloadRoot (namespace = NAMESPACE_URI, localPart = "getCountryRequest")

@ ResponsePayload

Public GetCountryResponse getCountry (@ RequestPayload GetCountryRequest request) {

GetCountryResponse response = new GetCountryResponse ()

Response.setCountry (countryRepository.findCountry (request.getName ()

Return response

}

Where @ PayloadRoot is provided by Spring WS, the processing method is selected, and the properties include namespace and localpart.

@ RequestPayload is provided by Spring WS, which means that the SOAP message will be bound to the request parameter.

@ ResponsePayload is provided by Spring WS, and the mapping returns the value to the response payload.

(6) configure web service bean

Inherit a webservice configuration class from WsConfigurerAdapter and annotate @ EnableWs, @ Configuration

For example:

@ EnableWs

@ Configuration

Public class WebServiceConfig extends WsConfigurerAdapter {

B, Custom DispatcherServlet bean

Spring WS uses a different servlet type to process SOAP messages, which is MessageDispatcherServlet.

You need to inject ApplicationContext into the method so that Spring WS can automatically detect Spring bean.

Renaming the MessageDispatcherServlet injection method does not replace the default DispatcherServlet bean of Spring Boot. The default bean provides services through the link point "/", and the custom MessageDispatcherServlet resets the link point through ServletRegistrationBean.

The previous @ Endpoint annotation has prompted DefaultMethodEndpointAdapter to set up the annotation-driven Spring WS programming model. This annotation-driven model is used here.

For example:

@ Bean

Public ServletRegistrationBean messageDispatcherServlet (ApplicationContext applicationContext) {

MessageDispatcherServlet servlet = new MessageDispatcherServlet ()

Servlet.setApplicationContext (applicationContext)

Servlet.setTransformWsdlLocations (true)

Return new ServletRegistrationBean (servlet, "/ ws/*")

}

C, build WSDL definition based on DefaultWsdl11Definition

DefaultWsdl11Definition uses the XsdSchema interface to display the WSDL1.1 standard.

For example:

@ Bean (name = "countries")

Public DefaultWsdl11Definition defaultWsdl11Definition (XsdSchema countriesSchema) {

DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition ()

Wsdl11Definition.setPortTypeName ("CountriesPort")

Wsdl11Definition.setLocationUri ("/ ws")

Wsdl11Definition.setTargetNamespace ("http://jiaxiaomei.com/test/soap-test");"

Wsdl11Definition.setSchema (countriesSchema)

Return wsdl11Definition

}

The attribute name of @ Bean actually specifies the file name of wsdl, so the wsdl file can be obtained from this link:

Http://:/ws/countries.wsdl

(7) build the Application class and note @ SpringBootApplication

After Build, start the service, create a request xml, and write a request to enter the SOAP.

For example:

Spain

Download curl, address: https://curl.haxx.se/, and set the bin directory to the environment variable path. Then, use curl to send the soap request on the command line, as follows:

Download libxml2 with three files, iconv-1.14-win32-x86_64.7z, zlib-1.2.8-win32-x86_64.7z, and libxml2-2.9.3-win32-x86_64.7z, at https://www.zlatkovic.com/pub/libxml/64bit/; unzip and put all three bin in the path environment variable. Then execute it on the command line:

Curl-- header "content-type: text/xml"-d @ request.xml http://localhost:8080/ws | xmllint-- format

This makes the soap response file more organized.

5. RESTful Web Service production service

Reference: https://spring.io/guides/gs/rest-service/ gives a practical example.

(1) create a new gradle project and modify the build.gradle

A. the dependencies for modification are:

Dependencies {

/ / This dependency is exported to consumers, that is to say found on their compile classpath.

/ / api 'org.springframework.boot:spring-boot-starter-web:2.1.0.RELEASE'

/ / This dependency is used internally, and not exposed to consumers on their own compile classpath.

Implementation 'org.springframework.boot:spring-boot-starter-web:2.1.0.RELEASE'

/ / spring-boot-starter-test based on JUnit test framework

TestImplementation 'org.springframework.boot:spring-boot-starter-test:2.1.0.RELEASE'

}

B. Modify the build script

Buildscript {

Repositories {

MavenCentral ()

}

Dependencies {

Classpath ("org.springframework.boot:spring-boot-gradle-plugin:2.1.0.RELEASE")

}

}

C, reference plug-in

Apply plugin: 'eclipse'

Apply plugin: 'idea'

Apply plugin: 'org.springframework.boot'

Apply plugin: 'io.spring.dependency-management'

D. Add jar package output information

BootJar {

BaseName = 'restfultest'

Version = '0.1.0'

}

E, add compatibility information

SourceCompatibility = 1.8

TargetCompatibility = 1.8

Refresh the project after saving (item right-click menu à gradle à refresh gradle project), prompt:

Modify the project gradle settings:

(2) create a new model

(3) create a new controller

@ RestController is introduced in Spring4, see "Annotation" in "5, Spring Boot" to label the class as a controller, where each method returns a model instead of a view.

The @ RequestMapping annotation maps the HTTP request http://host:port/msg to the annotated method.

@ RequestParam annotation binds the HTTP request parameter to the annotated method parameter (http://host:port/msg?name=).

Note: this is a RESTful web service controller, not a traditional MVC controller. This controller simply returns a model object, which data is written directly to HTTP response,MappingJackson2HttpMessageConverter using JSON to be automatically executed to support Jackson2. Traditional MVC controller uses view technology to convert data to html in server-side.

(4) create a new Application

(5) execution

Use the button in the upper left corner of Boot Dashboard to start the service.

Verify in Chrome:

VI. SOAP Web Service consumer services

Reference: https://spring.io/guides/gs/consuming-web-service/

(1) create a new maven project

Modify pom.xml

(2) write tasks to automatically generate classes from WSDL.

(3) create a web service client

Inherited from the WebServiceGatewaySupport class:

The getCountry method completes the task of SOAP data exchange.

Both GetCountryRequest and GetCountryResponse are generated automatically by jaxb.

WebServiceGatewaySupport's method getWebServiceTemplate gets the WebServiceTemplate, and then uses the marshalSendAndReceive method to actually complete the wsdl file reception and parsing.

This header is required when SoapActionCallback is used to obtain SOAPAction header,WSDL parsing, which contains elements.

(4) configure web service

Spring WS accesses XML requests through Jaxb2Marshaller in Spring Framework's OXM module.

Marshaller bean points to a collection of domain objects, converting between XML and POJOs.

CountryClient bean is used to configure the URI of web service and bind marshaller.

(5) configure the application entry class

VII. RESTful Web Service consumer services

Reference: https://spring.io/guides/gs/consuming-rest/

(1) create a new gradle project and modify the build.gradle as follows

(2) create a domain class, as follows:

(3) create an Application class, as follows:

The service address refers to "RESTful Web Service production service", and the output after execution is:

(4) transform Application class

Where @ Bean annotates restTemplate into the CommandLineRunner callback function.

Due to the conflict with port 8080 used by RESTful Web Service production Services, you need to add Application.yml as follows:

After startup, it is as follows:

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report