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-6-Spring Boot

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

Share

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

1 release not

GA= General Availability: the official release version, which is officially recommended

RCx=Release Candidate: candidate version, which is about to become an official release

SNAPSHOT: snapshot version, which can be used stably, but continues to improve

Mx=stands for milestone: milestone version, development version, unstable

1.x: latest release 1.5.17 GA, release date 2018.10.16)

2.x: the latest release is 2.0.6GA, the release date is 2018.10.16)

Version dependencies are as follows:

Spring boot version

Spring Framework

Jdk version

Maven version

Before version 1.2.0

six

three

1.2.0

4.1.3 +

six

3.2 +

1.2.1

4.1.3 +

seven

3.2 +

1.2.3

4.1.5 +

seven

3.2 +

1.3.4

4.2.6 +

seven

3.2 +

1.3.6

4.2.7 +

seven

3.2 +

1.3.7

4.2.7 +

seven

3.2 +

1.3.8

4.2.8 +

seven

3.2 +

1.4.0

4.3.2 +

seven

3.2 +

1.4.1

4.3.3

seven

3.2 +

1.4.2

4.3.4

seven

3.2 +

1.4.3

4.3.5

seven

3.2 +

1.4.4

4.3.6

seven

3.2 +

1.4.5

4.3.7

seven

3.2 +

1.4.6

4.3.8

seven

3.2 +

1.4.7

4.3.9

seven

3.2 +

1.5.0

4.3.6

seven

3.2 +

1.5.2

4.3.7

seven

3.2 +

1.5.3

4.3.8

seven

3.2 +

1.5.4

4.3.9

seven

3.2 +

1.5.5

4.3.10

seven

3.2 +

1.5.7

4.3.11

seven

3.2 +

1.5.8

4.3.12

seven

3.2 +

1.5.9

4.3.13

seven

3.2 +

2.0.0

5.0.2

eight

3.2 +

2 download and install

Eclipse 4.8.0 help Eclipse MarketPlace …

Select popularized Spring Tools 3 Add-on:

The restart takes effect after installation.

3 dependence

1, Java 8 or 9

2. Spring Framewok 5.0.10.RELEASE or above

3. Use maven3.2+ or gradle4.x to build

4. Servlet container uses tomcat8.5 or jetty9.4 or undertow1.4,servlet version 3.1

4 source code

1. SpringBoot source code location:

Https://github.com/spring-projects/spring-boot

Command-line compilation can have many fewer problems, and there will be a JDK problem once (see question 2 of maven 7), as follows:

D:\ eclipse\ workspace\ spring-boot\ spring-boot-project\ spring-boot > mvn clean install-Dmaven.test.skip=true

There are many problems with compiling in eclipse:

(1) Repository Path'd:\ eclipse\ workspace\ spring-boot\ spring-boot-project\ spring-boot-starters\ spring-boot-starter\ target\ classes' does not exist.

Classes is missing, just add it.

(2) Repository Path'd:\ eclipse\ workspace\ spring-boot\ spring-boot-project\ spring-boot-starters\ spring-boot-starter-logging\ target\ classes' does not exist.

Classes is missing, just add it.

(3) copy (include-loader-jar) on project spring-boot-loader-tools: Artifact has not been packaged yet. When used on reactor artifact, copy should be executed after packaging: see MDEP-187.

It doesn't affect the usage. Delete the package of the maven library (D:\ maven-repository\ org\ apache\ maven\ plugins\ maven-dependency-plugin) and download it again.

(4) test (default-test) on project spring-boot: There are test failures.

You need to test the code when executing maven-install. If there is an error in the test, report this error. The solution is:

Add a line after maven-surefire-plugin:

True

Another way is to find the reason for the failure of the test. Prompt: sslWantsClientAuthenticationSucceedsWithoutClientCertificate (org.springframework.boot.web.embedded.tomcat.TomcatReactiveWebServerFactoryTests) Time elapsed: 0.022 s later as follows:

Modify the project information and click on the next step:

Select the next step after selecting dependency:

This is a summary. The project is automatically generated after clicking finish, and the package needs to be downloaded automatically. It is recommended to set maven mirror to Aliyun.

Right click the project à debug as... à maven-build will have two problems successively, see section 7 maven question 1, question 2; you can right-click the project à debug as … When à Spring boot app starts, the above two problems will not occur.

Enter http://localhost:8080 in the browser chrome, as follows:

Add a controller, as follows

Verify in the browser as follows:

7 problem 1. Unable to find SpringApplication

The first method: do not use the maven that comes with eclipse, set up a new local warehouse, and run maven-install to solve the problem.

The second method: change the version of SpringBoot from 2.0.6 to 2.0.5

Org.springframework.boot

Spring-boot-starter-parent

2.0.5.RELEASE

Problem 2. Unable to introduce org.springframework.boot.autoconfigure.SpringBootApplication

Delete the autoconfigure from the local warehouse and run the project right-click menu maven à Update project.

Problem 3. Unable to introduce @ RestController,@RequestMapping

Right click on the code in eclipse and follow the prompts to solve the problem.

Problem 4. Unable to introduce @ SpringBootApplication

Delete the autoconfigure from the local warehouse and run the project right-click menu maven à Update project.

Problem 5: unable to read application.properties

Moving application.properties or application. Yml to the config directory, some people think that it is actually wrong to put it in the resources directory.

The official document says to put it in the following four directories:

(1) under the subdirectory "/ config" of the current directory

(2) under the current directory

(3) under the "/ config" package of the classpath root directory

(4) under the root directory of classpath

Problem 6: unable to access the link specified in @ RequestMapping

The reason is that the 1:Application class and the Controller class are no longer in the same package. The solution: put the Application class and the Controller class in the same package.

Question 7:Error creating bean with name 'userController': Unsatisfied dependency expressed through field' userService'. Validation failed for query for method public abstract java.util.List com.edison.dblib.UserRepository.findUser (java.lang.String)!

The reason is that the Hibernate used by JPA needs to pass the model name in the java instead of using the table name, so you need to put:

@ Query ("select id,username,sex,address from User u where u.username=:name")

List findUser (@ Param ("name") String username)

Change to:

@ Query ("select id,username,sex,address from UserModel u where u.username=:name")

List findUserModel (@ Param ("name") String username)

Question 8:Consider defining a bean of type 'com.edison.dblib.UserDao' in your configuration

Description:

Field userDao in com.edison.dblib.CustomUserService required a bean of type 'com.edison.dblib.UserDao' that could not be found.

Action:

Consider defining a bean of type 'com.edison.dblib.UserDao' in your configuration.

Solution: use @ Mapper annotations

/ / @ Repository

@ Mapper

Public interface UserDao {

Public SysUser findByUserName (String username)

}

Question 9:The server time zone value'I don't know,'is unrecognized or represents more than one time zone.

Solution: after connecting to URL, add? serverTimezone=UTC

8 logical diagram

9 Starter

Starter

Function

POM

Spring-boot-starter

Core initiator: auto configuration support, logging, YAML

Org.springframework.boot

Spring-boot-starter

Spring-boot-starter-activemq

Support for JMS messages based on Apache ActiveMQ

Org.springframework.boot

Spring-boot-starter-activemq

Spring-boot-starter-amqp

Support for Spring AMQP and RabbitMQ

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-aop

Implementation of AOP based on Spring AOP and AspectJ

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-artemis

Support for JMS messages based on Apache Artemis

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-batch

Support for Apache Batch

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-cache

Support for cache in Spring Framework

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-cloud-connectors

Support for Spring Cloud Connectors to simplify connectivity to cloud platforms, such as Cloud Foundry,Heroku

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-data-cassandra

Support for Spring Data Cassandra and Cassandra distributed databases

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-data-cassandra-reactive

Support for Spring Data Cassandra Reactive and Cassandra distributed databases

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-data-couchbase

Support for Spring Data Couchbase and Couchbase document databases

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-data-couchbase-reactive

Support for Spring Data Couchbase Reactive and Couchbase document databases

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-data-elasticsearch

Support for Spring Data Elasticsearch and Elasticsearch search and analysis engines

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-data-jpa

Support for Hibernate-based Spring Data JPA

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-data-ldap

Support for Spring Data LDAP

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-data-mongodb

Support for Spring Data MongoDB and MongoDB document databases

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-data-mongodb-reactive

Support for Spring Data MongoDB Reactive and MongoDB document databases

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-data-neo4j

Support for Spring Data Neo4j and Neo4j graphics databases

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-data-redis

Support for Spring Data redis and redis key-value databases

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-data- redis-reacive

Support for Spring Data redis reactive and redis in-memory databases

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-data-rest

Support for Spring Data rest and REST-based Spring Data data warehouse output

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-data-solr

Support for Spring Data solr and solr search engines

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-data-freemarker

Building MVC web applications based on freemarker View

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-groovy-templates

Building MVC web applications based on groovy templates View

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-hateosa

Construction of Hypermedia web Application based on RESTful based on Spring MVC and Spring HATEOSA

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-integration

Support for Spring integration

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-jdbc

Support for JDBC based on HikariCP connection pool

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-jersey

Build web application based on RESTful based on JAX-RS and Jersey. Alternative to spring-boot-starter-web

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-jooq

Access SQL database based on jOOQ. Can replace spring-boot-starter-jdbc or spring-boot-starter-data-jpa

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-json

Read and write JSON

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-jta-atomikos

JTA distributed transaction based on Atomikos

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-jta-bitronix

JTA distributed transaction based on Bitronix

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-jta-narayana

JTA distributed transaction based on narayana

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-mail

Support for JAVA Mail based on Spring Framework email sending

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-mustache

Building web applications based on mustache View

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-quartz

Implementation of Task Scheduler based on quartz

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-security

Support for Spring Security

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-test

Testing of Spring Boot applications based on Junit, Hamcrest or Mockito

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-thymeleaf

Building MVC web applications based on thymeleaf View

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-validation

Implementation of Java Bean check based on Hibernate Validator

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-web

Build RESTful-style web applications based on Spring MVC, using embedded tomcat as the default container

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-web-services

Use Spring Web Services

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-webflux

Construction of Webflux-style web Application based on Reactive Web function of Spring Framework

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-websocket

Construction of WebSocket Application based on Websocket function of Spring Framework

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-actuator

Driver, used for production preparation, provides application monitoring and management functions. Unlike the application initiator above this entry, this is the production initiator, the only

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-jetty

Technology starter. Use jetty as the embedded servlet container. Can replace spring-boot-starter-tomcat

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-log4j2

Technology starter. Use log4j2 as the logging component. Can replace spring-boot-starter-logging

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter- logging

Technology starter. Use Logback as the logging component. Default log initiator

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-reactive-netty

Technology starter. Using Reactive Netty as an embedded reactive Http server

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-tomcat

Technology starter. Use tomcat as the embedded servlet container. Default servlet container used by spring-boot-starter-web

Org.springframework.boot

Spring-boot-starter-?

Spring-boot-starter-undertow

Technology starter. Use undertow as the embedded servlet container. Alternative to spring-boot-starter-tomcat

Org.springframework.boot

Spring-boot-starter-?

10 Annotation

1. Boot comments

Notes

explain

@ SpringBootApplication

Automatically include @ Configuration, @ EnableAutoConfiguration, @ EnableWebMvc, @ ComponentScan. Belongs to the Spring Boot comment.

@ SpringBootTest

An annotation introduced by SpringBoot for testing since version 1.4.0. The classes attribute specifies the startup class, and SpringBootTest.WebEnvironment.RANDOM_PORT is often used with @ LocalServerPort in the test class when injecting properties. A port number is randomly generated.

@ SpringBootConfiguration

Inherited from @ Configuration. It is recommended to use @ SpringBootConfiguration instead of @ Configuration in SpringBoot projects

@ Configuration

Annotate the application context. Equivalent to Spring Framework's XML configuration file. You can use annotations for type safety checking

@ EnableAutoConfiguration

Automatic configuration. Tell SpringBoot to start adding classpath-based bean and other bean with different property settings

@ EnableWebMvc

Enable web applications to activate key behaviors such as setting DispatcherServlet. When SpringBoot discovers that classpath has spring-webmvc, it automatically increases the annotation.

@ ComponentScan

Automatically find other components, configurations, and services that exist in the Java package. Bean can be assembled automatically.

@ Component

Can be used with CommandLineRunner. Perform basic tasks after the SpringBoot application starts. Note on the class, indicating that the generic bean,value does not write the default class name in lowercase.

@ Service

Business layer bean, annotated on the class

@ Repository

Data access layer bean, annotated on the class

@ Controller

Control layer bean, annotated on the class

@ ImportResource

Call XML configuration file

@ Autowired

The default byType is injected by type (DI), and the default property required=true means that an exception is automatically thrown when a matching bean is not found. Combined with @ Qualifier, the automatic injection changes from byType to byName. Comments are made on member variables, methods, and constructors. Belong to Spring Framework

@ Resource

Default byName is injected by name (DI). Comments are made on member variables, methods, and constructors. Comments belonging to Java EE

@ Bean

Declares that the current method returns a bean. Note on the method.

@ Scope

Specifies how the bean instance is created. Comment on the class. The creation methods include the following:

(1) singleton: indicates a singleton in the spring container. A unique instance is always returned when the bean is obtained through the spring container. To specify @ Scope, this is the default

(2) prototype: a new object is generated every time a bean is obtained.

(3) request: valid within a http request (only applicable to web applications)

(4) session: indicates that it is valid within a user session (for web applications only)

(5) globalSession: valid within a global session (for web applications only)

@ value

Read the value from the configuration file. Comment on the variable. For example: @ Value (value = "# {message}")

@ ConfigurationProperties

Assign values to objects to convert annotations to objects

@ Profile

Select instantiation in different cases

@ RestController

Automatically include @ Controller and @ ResponseBody

@ ResponseBody

The returned result is directly written into the HTTP response body (ResponseBody), which is generally used when getting data asynchronously. After @ RequestMapping, the return value is usually resolved as a jump path, and the return result is changed from the jump path to written directly into the body of the HTTP response when @ Responsebody is added. Comments are made in the method.

@ Controller

Used to define the controller class. In the spring project, the controller is responsible for forwarding the URL request sent by the user to the corresponding service interface (service layer). Annotations are in the class, with @ RequestMapping.

@ RequestBody

This annotation is used to read the body part of the data requested by Request, parse it using the HttpMessageConverter configured by default, and then bind the corresponding data to the object to be returned; then bind the object data returned by HttpMessageConverter to the parameters of the method in controller. The judgment and treatment of GET, POST and PUT are different.

@ PathVariable

Bind the Request parameter to the parameter of the Controller method. Required=false can not throw an exception when value does not exist. URL: http://host:port/path/ parameter valu

@ RequestParam

Bind the Request parameter to the parameter of the Controller method. Required=false can not throw an exception when value does not exist. URL: http://host:port/path? Parameter name = parameter valu

@ RequestMapping

The attributes are value (default) and method,consumes,produces,params,headers.

Value: request relative url address

Method: method type. If ignored, get or post is automatically determined.

Consumes: the type of content submitted

Produces: the type of content returned

Params: parameters that must be included in the request

Headers: the header that the request must contain

@ GetMapping

Same as @ RequestMapping (method = RequestMethod.GET)

@ PutMapping

Same as @ RequestMapping (method = RequestMethod.PUT)

@ PostMapping

Same as @ RequestMapping (method = RequestMethod.POST)

@ DeleteMapping

Same as @ RequestMapping (method = RequestMethod.DELTE)

@ EnableCaching

Join Cache Manager

@ SuppressWarning

Remove warning

@ Modifying

Indicates that the database operation is an addition, deletion or modification. Use with @ Transactional

@ Query

Specifies a custom query statement. Support for JPQL or native SQL

@ RepositoryRestResource

Use with spring-boot-starter-data-rest. After Spring Data REST automatically creates an implementation of this interface, the @ RepositoryRestResource annotation tells Spring MVC to create a RESTful entry point at path.

@ RunWith

@ AutoConfigureMockMvc

@ Test

@ AutoConfigureWebTestClient

@ DirtiesContext

@ MockBean

@ JsonTest

@ WebMvcTest

@ WebFluxTest

@ DataJpaTest

@ AutoConfigureTestDatabase

@ JooqTest

@ DataMongoTest

@ DataNeo4jTest

@ DataRedisTest

@ JdbcTest

@ Import

@ AutoConfigureRestDocs

@ LocalServerPort

@ TestConfiguration

@ Override

@ ImportAutoConfiguration

@ EnableBatchProcessing

@ ContextConfiguration

@ Value

@ PayloadRoot

@ ResponsePayload

@ Endpoint

@ RequestPayload

@ JsonCreator

@ JsonProperty

2. JPA comments

Notes

explain

@ Entity

Declare the class as an entity or table.

@ Table

Declare the table name. Used with @ Entity to indicate that the table name and entity name are different

@ Basic

Specify individual fields that are not explicitly constrained.

@ Embedded

Specifies that the class or its value is an entity attribute of an instance of an embeddable class.

@ Id

The property of the specified class that is used to identify (the primary key in a table).

@ GeneratedValue

Specifies how to identify properties that can be initialized, such as values obtained automatically, manually, or from an ordered list. Strategy=IDENTITY: self-growing, strategy=AUTO: automatic (default), strategy=SEQUENCE: using @ SequenceGenerator sequence generator, strategy=TABLE: using table generation

@ Transient

Indicates that it is not persistent, that is, the value is never stored in the database. Without this comment, it means the default @ Basic

@ Basic

Lasting. Fetch=FetchType.LAZY denotes loading mode

@ Column

Specifies the persistent property bar property. Properties name: field name, unique: unique, nullable: empty, Length: length, insertable: pluggable, updateable: updatable, columnDifinition:DDL,secondaryTable: from table name.

@ Temporal

Used with @ Column. Attribute value:TemporalType.DATE: date, TemporalType.TIME: time, TemporalType.TIMESTAMP: timestamp

@ JsonIgnore

The effect is that some attributes in the Java bean are ignored when json serialization, and both serialization and deserialization are affected.

@ JsonIgnoreProperties

Class comments, the function is to ignore some properties in java bean when json serialization, serialization and deserialization are affected

@ JsonFormat

For properties or methods (preferably on properties), it is convenient to convert the Date type directly to the schema we want, such as @ JsonFormat (pattern = "yyyy-MM-dd HH-mm-ss")

@ JsonSerialize

This annotation is used on properties or getter methods to embed our custom code when serializing, such as limiting two decimal places after a double serialization.

@ JsonDeserialize

This annotation is used on properties or setter methods to embed our custom code when deserializing, similar to @ JsonSerialize above

@ JsonManagedReference

Put in the parent class

@ JsonBackReference

Put in a subclass

@ SequenceGenerator

Specifies the value of the attribute specified in the @ GeneratedValue annotation. It creates a sequence.

@ TableGenerator

Specifies the value generator for the specified attribute annotated in @ GeneratedValue. It creates the values generated by the table.

@ AccessType

This type of annotation is used to set the access type. If you set @ AccessType (FIELD), you can access variables directly and do not need getter and setter, but must be public. If you set @ AccessType (PROPERTY), access the variables of Entity through the getter and setter methods.

@ JoinColumn

Specifies an entity organization or collection of entities. This is used in many-to-one and one-to-many associations.

@ UniqueConstraint

The specified fields and unique constraints for the primary or secondary table.

@ ColumnResult

Refer to the column names in the SQL query that uses the select clause.

@ ManyToMany

The many-to-many one-to-many relationship between join tables is defined. Corresponding hibernate profile

@ ManyToOne

The many-to-one relationship between join tables is defined. Corresponding hibernate profile

@ OneToMany

Defines that there is an one-to-many relationship between join tables. Corresponding hibernate profile

@ OneToOne

Defines an one-to-one relationship between join tables. Corresponding hibernate profile

@ NamedQueries

Specifies a list of named queries.

@ NamedQuery

Specifies a query with a static name.

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