Detailed notes SpringBoot most comprehensive (integrated ultra-detailed version) (rpm)

First, the notes listed below (equipped with a sound interpretation) ------ (ctrl + F can be used to search oh ~ ~ ~ ~)

@SpringBootApplication: contains @ ComponentScan, @ Configuration and @EnableAutoConfiguration comment. among them

@ComponentScan: Let spring Boot Configuration class to scan and add it to the program context.

@Configuration: equivalent to the spring XML configuration file; the use of Java code can check the type of security.

@EnableAutoConfiguration: automatic configuration.

@ComponentScan: scanning assembly, and assembling a number of automatic discovery Bean.

@Component can be used with CommandLineRunner used to perform some basic tasks after the program starts.

@RestController: the annotations are @Controller @ResponseBody and collection, the controller indicates this is the bean, and the return value of the function is filled directly into the body of the HTTP response, the controller is REST style.

@Autowired: automatic import.

@PathVariable: acquisition parameters.

@JsonBackReference: nested outside the chain to solve the problem.

@RepositoryRestResourcepublic: with the spring-boot-starter-data-rest used.

Second, comment Comments (explained in more detail with the snippet intuitive)

@SpringBootApplication: Affirming let spring boot automatically makes the necessary configuration to the program, this configuration is equivalent to: @Configuration, @ EnableAutoConfiguration and @ComponentScan three configurations.

Package com.example.myproject. 1;
2 Import org.springframework.boot.SpringApplication;
. 3 Import org.springframework.boot.autoconfigure.SpringBootApplication;
. 4
. 5 @SpringBootApplication @Configuration @EnableAutoConfiguration @ComponentScan AS // Same
. 6 {public class the Application
. 7 static void main public (String [] args) {
;. 8 SpringApplication.run (Application.class, args)
. 9}
10}
when the result indicates that the method returns directly written HTTP response body, the data is generally acquired asynchronously: @ResponseBody used for constructing the api RESTful. @RequestMapping after use, the return value is typically resolved as the jump path and, with the results returned @esponsebody not be interpreted as the jump path, but directly written in the HTTP response body. Such as asynchronous get json data, after adding @Responsebody, it will return json data directly. The Notes will generally be used in conjunction with @RequestMapping. Sample code:

@RequestMapping. 1 ( "/ Test")
2 @ResponseBody
. 3 public String Test () {
. 4 return "OK";
. 5}
@Controller: a controller for defining classes in the spring by the controller responsible for the project will be sent to the user URL request is forwarded to the corresponding service interface (service layer), generally in the annotation class annotated with the conventional method requires @RequestMapping. Sample code:

1 @Controller
2 @RequestMapping(“/demoInfo”)
3 public class DemoController {
4 @Autowired
5 private DemoInfoService demoInfoService;
6
7 @RequestMapping("/hello")
8 public String hello(Map<String,Object> map){
9 System.out.println("DemoController.hello()");
10 map.put("hello","from TemplateController.helloHtml");
11 //会使用hello.html或者hello.ftl模板进行渲染显示.
12 return"/hello";
13 }
14 }

@RestController: a control layer label assembly (e.g., the action struts), @ ResponseBody @Controller and the collection. Sample code:

Package com.kfit.demo.web. 1;
2
. 3 Import org.springframework.web.bind.annotation.RequestMapping;
. 4 Import org.springframework.web.bind.annotation.RestController;
. 5
. 6
. 7 @RestController
. 8 @RequestMapping ( "/ demoInfo2 ")
. 9 publicclass DemoController2 {
10
. 11 @RequestMapping (" / Test ")
12 is public String Test () {
13 is return" OK ";
14}
15}
@RequestMapping: providing routing information to the Controller is responsible for the specific URL of the function mapping.

@EnableAutoConfiguration: SpringBoot automatic configuration (auto-configuration): attempts to automatically configure your application based on Spring jar rely on your add. For example, if your classpath under HSQLDB, and you do not have to manually configure any database connections beans, then we will automatically configure a type of memory (in-memory) database. "You can add notes to a @EnableAutoConfiguration or @SpringBootApplication @Configuration class up select automatic configuration. If you find that a particular application automatically configures classes you do not want, you can use negative attributes @EnableAutoConfiguration comment to disable them.

@ComponentScan: indicates the type of automatic discovery scanning assembly. Personal understanding is equivalent to, if the class has to scan these annotations @ Component, @ Controller, @ Service, etc., and registered as Bean, Spring can automatically collect all the components, including @Configuration class. We often use @ComponentScan annotation search beans, combined with @Autowired notes import. Spring can automatically collect all the components, including @Configuration class. We often use @ComponentScan annotation search beans, combined with @Autowired notes import. If no words, Spring Boot will start scanning the next class pack and use the @ Service, @ Repository annotation and other sub-package in the class lies.

@Configuration: equivalent to the traditional xml configuration file, if you need to use some third-party library xml file, still recommended as the main class configuration items by @Configuration class - can be used to load xml configuration file @ImportResource comment.

@Import: used to introduce other configuration class.

@ImportResource: used to load xml configuration file.

@Autowired: automatically import dependent bean

@Service: General assembly of the service layer for modifying

@Repository: Use @Repository annotation can ensure DAO abnormal or repositories provide translation, this annotation modified or repositories DAO class will be found and configured ComponetScan, also do not need to provide XML configuration items for them.

@Bean: Tagging with @Bean equivalent bean XML configured.

@Value: injecting value Spring boot application.properties configuration attributes. Sample code:

@Value. 1 (value = "#} {Message")
2 Message String Private;
@Inject: equivalent to the default @Autowired, but there is no required attribute;

@Component: refers to the components when the components are classified bad, we can use this annotation to mark.

@Bean: XML equivalent of the above, in the method, rather than a class, meaning that produces a bean, and manage to spring.

@AutoWired: automatically import dependent bean. byType way. Bean configured to make use, completed properties, assembly method, it can be labeled class fields, methods and constructors, the completion of the automatic assembly. When coupled with (required = false), even if can not find the bean is not an error.

@Qualifier: when a plurality of the same type of Bean, can be specified @Qualifier ( "name"). Used in conjunction with @Autowired. In addition to defining @Qualifier descriptor name according to the injection, but can be more fine-grained control how the selected candidates, specifically used as follows:

@Autowired. 1
2 @Qualifier (value = "demoInfoService")
. 3 Private DemoInfoService demoInfoService;
@Resource (name = "name", type = "type"): not within the braces, the default byName. A similar thing with @Autowired dry.

Three, JPA annotations

@Entity: @Table (name = ""): indicates that this is an entity class. Both generally used jpa annotations using a general, but if the table name and the name of the entity, then the same class, @ Table may be omitted

@MappedSuperClass: is used in the determination of the parent entity. Properties sub-class of the parent class can be inherited.

@NoRepositoryBean: generally used as the parent class repository, this annotation, spring not to instantiate the repository.

@Column: field name and column names the same, it may be omitted.

@Id: indicates that the primary key attribute.

@GeneratedValue (strategy = GenerationType.SEQUENCE, generator = "repair_seq"): is a front key generation strategy sequence (may be Auto, IDENTITY, native, etc., represents Auto switch between a plurality of databases), the name of the specified sequence is repair_seq.

@SequenceGeneretor (name = "repair_seq", sequenceName = "seq_repair", allocationSize = 1): name is the name of the sequence to use, the name of the database sequence is sequenceName, two names may coincide.

@Transient: indicates that the property is not mapped to a field in a database table, ORM framework will ignore the attributes. If a property is not a field mapping database tables, be sure to mark it as @Transient, otherwise, ORM framework annotated as its default @Basic. @Basic (fetch = FetchType.LAZY): loading the entity may specify tag attributes

@JsonIgnore: the role is json serialized Java bean will ignore some of the properties, serialization and de-serialization are affected.

@JoinColumn (name = "loginId"): one: This table to the foreign key in another table. Many: foreign key to another table in this table.

@ OneToOne, @ OneToMany, @ ManyToOne: hibernate configuration file corresponds to one to one, one to many, many to one.

Four, springMVC related notes

@RequestMapping: @RequestMapping ( "/ path" ) indicates that the controller handles all "/ path" of the request UR L. RequestMapping is a process for annotation request address mapping, it can be used for class or method.
For the class, all the methods in response to the request class are represented in the address as the parent path. This note has six attributes:
params: Specifies the request must contain certain parameter values, before allowing the processing method.
headers: Specifies the request must contain certain specified header value, in order for this method to process the request.
value: actual address assignment request, the designated address may be a URI Template mode
method: method specifies the type of request, GET, POST, PUT, DELETE and so
consumes: Submit content type (Content-Type) specified processing request, such as application / JSON, text / HTML;
Produces: content type of the returned only when the head (the Accept) the request includes a request type specifies the type will return to

@RequestParam: parameters used in the previous method.
@RequestParam
String request.getParameter A = ( "A").

@PathVariable: path variable. Such as

@RequestMapping. 1 ( "User / GET / MAC / macAddress {}")
2 getByMacAddress public String (String @PathVariable macAddress) {
. 3 // do something;
. 4}
as parameters to be the same as the name of the braces.

Fifth, global exception handler

@ControllerAdvice: contains @Component. It can be scanned. Unified handle exceptions.

@ExceptionHandler (Exception.class): represents encountered this exception is to perform the following method is used in the above methods.

Sixth, the project specific configuration parsing and environment

@MappedSuperclass:
1. @ MappedSuperclass annotated with a parent class above, is used to identify the parent class

Class 2. @ MappedSuperclass identified said it can not be mapped to a database table, because it is not a complete entity class, but it has attributes can be mapped in a subclass of database tables used in

Class 3. @ MappedSuperclass identified or can not have @Entity @Table comment

@Column:

1. @Column required before the database table when the properties of the entity mapped thereto a different name column labeled described, this property is usually placed entity attribute declaration statement, and may also be used with labeled @Id.

2. @ Column marked common properties be name, or for setting a mapping database table column name. In addition, the label further comprises a plurality of additional attributes, such as: unique, nullable, length, precision and the like. details as follows:

1 name attributes: name attribute defines the name of the label field in the database table corresponding to the fields
2 unique attributes: unique attribute indicates whether the field is a unique identifier defaults to false, if a table has a field that uniquely identifies, then both the marker may be used, may be used in the annotation @Table @UniqueConstraint
. 3 Nullable properties: nullable attribute indicates whether the field can be null value, the default is to true
. 4 Insertable properties: insertable attribute indicates when using "iNSERT" statement to insert data, whether an insert value of the field
. 5 updateable properties: updateable attribute indicates when using the "uPDATE" statement to insert the data, whether to update the value of the field
6 insertable and updateable properties: generally used for read-only attribute, for example, primary and foreign keys etc. these fields are typically generated automatically
7 columnDefinition properties: columnDefinition create a table showing the properties of the field created by the SQL statement for general use by the Entity table definition, if the database table has been built, the property is not necessary use
8 table attributes: table Definition of the table containing the current field
9 length properties: length property represents the length field when the type field is varchar, the attribute is valid, the default is 255 characters
10 precision properties and scale attributes: precision properties and scale property together represent precision, when the field type is double, precision of the total length value, scale the number of bits occupied by the decimal point
as follows:
1.double types are mapped in the database for the double type, and scale properties Precision invalid
2.double type if the specified numeric type columnDefinition attribute specified as a decimal precision and is subject to final columnDefinition
3.BigDecimal type mapping in the database type decimal, precision and scale properties effective
4.precision scale and only valid attribute types BigDecimal

3. @ Column annotation columnDefinition properties: This field indicates the actual type in the database generally ORM framework can automatically determine the type field in the database according to the attribute types, but still can not be determined for the Date type database field type whether DATE, TIME. or TIMESTAMP. Moreover, String default mapping type is VARCHAR, BLOB or TEXT field types for a particular database if you want to map to the String type.

4. @ Column before labeling methods may also be placed getter properties

@Getter and @Setter (Lombok is)
@Setter: annotations on attributes; @Getter provided a method of setting attributes: annotation on the property; property provides for the method of getting
extended:
. 1 @Data: annotation on class; class provides all of the properties getting and setting methods, also provided equals, canEqual, hashCode, toString method
2
. 3 @Setter: annotations on attribute; property provides for the setting method
. 4
. 5 @Getter: annotation on the property; getting provides a method for the property
. 6
. 7 @ Log4j2: annotation on the class; log4j log object provides a class attribute called the log, and the like annotation @ log4j
. 8
. 9 @NoArgsConstructor: annotation on the class; class provides a constructor with no arguments
10
. 11 @AllArgsConstructor: annotations on the like; a whole class constructor parameter
12 is
13 is @EqualsAndHashCode: by default, all non-transitory use (non-transient) and non-static (non-static) and equals hascode field generating method, You can specify which attributes specific use.
14
15 @toString: generating toString method, by default, will output class names, all attributes, output attributes in the order, separated by commas.
16
@NoArgsConstructor 17, @RequiredArgsConstructor and @AllArgsConstructor
18 no-argument constructor, some parameters constructor, the whole argument constructor, when we need more overloaded constructor, our only handwritten
19
20 @NonNull: annotation properties on, if annotated, it must not be Null
21
22 @val: Notes on the property, if the annotation is set to the final type, you can view the source code annotation know
@PreUpdate and @PrePersist
 
@PreUpdate
1. for the corresponding life cycle events specified callback method.
2. The annotation may be applied to the entity class, the superclass or callback listener class mapping.
3. setter for updating attributes of the entity if the entity for each update, you can use @PreUpdate comment.
4. Note that, you do not have to explicitly update the properties of each update user entity.
5.preUpdate does not allow you to change your entity. You can only use the pass to set computing to change the event to modify the original field values.
 
@PrePersist
1. Check @PrePersist notes to help you automatically fills entity attributes before persistence.
2. can be used to record some unrelated business fields when using jpa, such as last updated, and so on. Life-cycle approach Notes (delete no life cycle events)
is called before 3. @ PrePersist save, it can return a DBObject instead of an empty @PostPersist save to be called after datastore
4. @ PostLoad is called @EntityListeners after Entity is mapped lifecycle events outside designated implementing class
Entity Bean lifecycle callbacks

Tagging: @PrePersist @PostPersist @PreRemove @PostRemove @PreUpdate @PostUpdate @PostLoad .
They mark before a certain method without any parameters. These labeling methods in the state of the entity is changed before and after the call, corresponding to the interceptor;
pre showing a state before the handoff trigger, said trigger POST after the handover.
@PostLoad event trigger in the following cases:
1. execution EntityManager.find () or getreference () method to load an entity;
after 2. Do JPA QL queries;
3. EntityManager.refresh () method is called after.
@PrePersist and @PostPersist event in the entity object into the database during the occurrence;
@PrePersist event occurs after the call EntityManager.persist () method immediately cascaded to save this event also occurs at this time of the data has not been inserted into the real database.
@PostPersist event occurs after the data has been inserted into the database.
@PreUpdate @PostUpdate and trigger events caused by the update entity, @PreUpdate event trigger synchronized to the database before state entities, not real data at this time to update the database.
@PostUpdate event state entities synchronized to the database after triggering, synchronization occurs when the transaction commits.
@PreRemove and @PostRemove trigger event is caused by deletion entity, @ PreRemove event triggers from the database before deleting the entity, called EntityManager.remove () method or cascade delete
 
When you perform a variety of methods of persistence, the state entity will change, change of state will lead to different life cycle events. These events can use a different comment character to indicate the callback function occurs.

@ Javax.persistence.PostLoad: after loading.

@ Javax.persistence.PrePersist: persistence ago.

@ Javax.persistence.PostPersist: persistence after.

@ Javax.persistence.PreUpdate: before updating.

After updating: @ javax.persistence.PostUpdate.

@ Javax.persistence.PreRemove: before deleting.

@ Javax.persistence.PostRemove: After deleting.

 
1) database query

@PostLoad events triggered in the following cases:

Performing the EntityManager.find () or getReference () method of an entity after loading.

After JPQL query execution.

EntityManager.refresh () method gets called.

2) inserted into the database

@PrePersist and @PostPersist event in the entity object into the database occurs during:

@PrePersist the incident immediately after the call to persist () method, then the data has not really inserted into the database.

@PostPersist event occurs after the data has been inserted into the database.

3) Database Update

@PreUpdate @PostUpdate and trigger events caused by the update entity:

@PreUpdate event before state entities synchronized to the database trigger, this time the data has not really been updated to the database.

@PostUpdate event after the state entity to database synchronization trigger, synchronization occurs when the transaction commits.

4) Delete database

@PreRemove @PostRemove and trigger events caused by the deletion entities:

@PreRemove event is fired before the entity from the database is deleted, calling remove () method removes occurs when, at this time the data is not really deleted from the database.

@PostRemove event is triggered after the entity is deleted from the database.

& @AllArgsConstructor @NoArgsConstructor (Lombok)
@NoArgsConstructor, provides a constructor with no arguments.

@AllArgsConstructor, provides a full-argument constructor.

& @Bean @Configuration
1. @ marked on the Configuration class, such as a spring corresponding to the xml configuration file
<Beans>
, function as: a container disposed spring (application contexts)
. 1 Package com.test.spring.support .configuration;
2
. 3 @Configuration
. 4 TestConfiguration {public class
. 5 public TestConfiguration () {
. 6 System.out.println ( "Spring container startup initialization ...");
7}
8}
 

相当于
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
4 xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
5 xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="
6 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
7 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
Http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd 8
9 http://www.springframework.org/schema/jee HTTP : //www.springframework.org/schema/jee/spring-jee-4.0.xsd
10 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring- 4.0.xsd-TX
. 11 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
12 is http://www.springframework.org / Schema / Task http://www.springframework.org/schema/task/spring-task-4.0.xsd "the lazy-default-the init =" to false ">
13 is
14
15 </ Beans>
primary test method:
. 1 Package com.test.spring.support.configuration;
2
. 3 {public class the testMain
Public static void main. 4 (String [] args) {
. 5
Spring loading container 6 // @ Configuration annotation, ClassPathXmlApplicationContext replaced with AnnotationConfigApplicationContext
. 7 the ApplicationContext context = new new AnnotationConfigApplicationContext (TestConfiguration.class);
. 8
. 9 // if loading spring-context .xml file:
10 // the ClassPathXmlApplicationContext the ApplicationContext context = new new ( "Spring-context.xml");
. 11}
12 is}
from the method of operation of the main results can be seen, spring container has started up:

1 August 11, 2016 12:04:11 pm prepareRefresh org.springframework.context.annotation.AnnotationConfigApplicationContext
2 Information: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@203e25d3: startup date [Thu Aug 11 12:04:11 CST 2016]; the root of context Hierarchy
. 3 Spring container startup initialization. . .
2. @ Bean marked on the method (the method returns an instance), xml configuration file is equivalent to the spring in the <bean>, function as: registration bean object

bean class:

1 package com.test.spring.support.configuration;
2
3 public class TestBean {
4
5 public void sayHello(){
6 System.out.println("TestBean sayHello...");
7 }
8
9 public String toString(){
10 return "username:"+this.username+",url:"+this.url+",password:"+this.password;
11 }
12
13 public void start(){
14 System.out.println("TestBean 初始化。。。");
15 }
16
17 public void cleanUp(){
18 System.out.println("TestBean 销毁。。。");
19 }
20 }
配置类:

Package com.test.spring.support.configuration. 1;
2
. 3 @Configuration
. 4 TestConfiguration {public class
. 5 public TestConfiguration () {
. 6 System.out.println ( "Spring container startup initialization ...");
7}
. 8
9 / / @ bean annotation registration bean, and can specify initialization and destruction methods
10 // @ bean (name = "testNean", initMethod = "Start", destroyMethod = "cleanUp")
11 @Bean
12 the @Scope ( "prototype")
13 TestBean the testBean public () {
14 return new new TestBean ();
15}
16}
master class test method:

Package com.test.spring.support.configuration. 1;
2
. 3 the testMain {public class
. 4 public static void main (String [] args) {
. 5 the ApplicationContext context = new new AnnotationConfigApplicationContext (TestConfiguration.class);
. 6 // Get the bean
. 7 TB TestBean context.getBean = ( "the testBean");
. 8 tb.sayHello ();
. 9}
10}
Note:
(. 1), on the return annotation @ bean example of a method, if the name is not specified by @Bean bean, and the default the method of the same name label;
(2), the default scope @ bean annotation singleton scope single embodiment, may be set by the prototype scope @Scope ( "the prototype");
(. 3), since the effect is a registered bean @Bean objects, can use the @ Component, @ Controller, @ Service , @ Ripository and other annotation registration bean, of course, need to be configured to automatically scan @ComponentScan comment.

bean class:

1 package com.test.spring.support.configuration;
2
3 //添加注册bean的注解
4 @Component
5 public class TestBean {
6
7 public void sayHello(){
8 System.out.println("TestBean sayHello...");
9 }
10
11 public String toString(){
12 return "username:"+this.username+",url:"+this.url+",password:"+this.password;
13 }
14 }
配置类:

1 // Open annotation configuration
2 @Configuration
. 3 // add annotations automatic scanning, basePackages package path to TestBean
. 4 @ComponentScan (basePackages = "com.test.spring.support.configuration")
. 5 TestConfiguration {public class
. 6 public TestConfiguration () {
. 7 System.out.println ( "Spring container startup initialization ...");
8}
. 9
10 @ bean cancel registration annotation @Bean way
. 11 @ @ bean
12 is the Scope @ @ ( "the prototype")
13 is / / public TestBean the testBean () {
14 // return new new TestBean ();
15} //
16}
primary method of obtaining test bean objects:

The testMain {public class. 1
2 public static void main (String [] args) {
. 3 the ApplicationContext context = new new AnnotationConfigApplicationContext (TestConfiguration.class);
. 4 // Get the bean
. 5 TestBean context.getBean TB = ( "the testBean");
. 6 TB. the sayHello ();
. 7}
. 8}
the sayHello () method is invoked normally.

Use Spring @Configuration annotation instead of bean configuration
The following is a typical Spring configuration file (application-config.xml):

1 <beans>
2 <bean id="orderService" class="com.acme.OrderService"/>
3 <constructor-arg ref="orderRepository"/>
4 </bean>
5 <bean id="orderRepository" class="com.acme.OrderRepository"/>
6 <constructor-arg ref="dataSource"/>
7 </bean>
8 </beans>
然后就可以像这样来使用bean:

CTX = the ClassPathXmlApplicationContext the ApplicationContext new new. 1 ( "the config.xml-file application");
2 = OrderService orderService (OrderService) ctx.getBean ( "orderService");
Now Spring Java Configuration provides a solution for this project are assembled through the bean java code :

1 @Configuration
2 public class ApplicationConfig {
3
4 public @Bean OrderService orderService() {
5 return new OrderService(orderRepository());
6 }
7
8 public @Bean OrderRepository orderRepository() {
9 return new OrderRepository(dataSource());
10 }
11
12 public @Bean DataSource dataSource() {
13 // instantiate and return an new DataSource …
14 }
15 }
然后就可以像这样来使用bean:

JavaConfigApplicationContext ctx = new new JavaConfigApplicationContext 1 (ApplicationConfig.class);
2 = OrderService orderService ctx.getBean (OrderService.class);
notes the advantage of the following:

     1. pure java code, does not require complicated configuration xml file

     2. In the configuration may also enjoy the benefits of object-oriented brought

     3. Type the security of the reconstruction can provide good support

     4. At the same time reduce the complexity of the configuration file can also enjoy the functionality provided by the container springIoC
---------------------
description: https: //blog.csdn.net/ weixin_40753536 / article / details / 81285046 

Guess you like

Origin www.cnblogs.com/NetPig/p/10947708.html