3rdstage's Wiki
Tag: Source edit
 
(87 intermediate revisions by the same user not shown)
Line 21: Line 21:
 
===References===
 
===References===
   
  +
* [https://docs.spring.io/spring-framework/docs/5.3.x/reference/html/ Spring Framework 5.3 Reference Documentation]
  +
* [https://docs.spring.io/spring-framework/docs/5.3.x/javadoc-api/ Spring Framework 5.3 API]
 
* [https://docs.spring.io/spring/docs/5.0.x/spring-framework-reference/ Spring Framework 5.0 Reference Documentation]
 
* [https://docs.spring.io/spring/docs/5.0.x/spring-framework-reference/ Spring Framework 5.0 Reference Documentation]
 
* [https://docs.spring.io/spring/docs/5.0.x/javadoc-api/ Spring Framework 5.0 API]
 
* [https://docs.spring.io/spring/docs/5.0.x/javadoc-api/ Spring Framework 5.0 API]
Line 37: Line 39:
 
* [http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/ Spring Framework 3.0 Reference Documentation]
 
* [http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/ Spring Framework 3.0 Reference Documentation]
 
* [http://docs.spring.io/spring/docs/3.0.x/javadoc-api/ Spring Framework 3.0 API]
 
* [http://docs.spring.io/spring/docs/3.0.x/javadoc-api/ Spring Framework 3.0 API]
  +
  +
* [https://howtodoinjava.com/spring-5-tutorial/ Spring 5 Tutorial]
   
 
===General===
 
===General===
Line 89: Line 93:
 
===Container===
 
===Container===
   
* [http://docs.spring.io/spring/docs/4.0.x/javadoc-api/index.html?org/springframework/context/ConfigurableApplicationContext.html '''<code>ConfigurableApplicationContext</code>''']
+
* [https://docs.spring.io/spring/docs/5.1.x/javadoc-api/index.html?org/springframework/context/ApplicationContext.html <tt>ApplicationContext</tt>]
  +
** Prefer <code>ConfigurableApplicationContext</code> to <code>ApplicationContext</code>
 
  +
<syntaxhighlight lang='text' enclose='div' style='margin-left:40px'>
** Pay attention to <code>registerShutdownHook()</code> method.
 
  +
EnvironmentCapable <--------------------------------+
* [http://docs.spring.io/spring/docs/4.0.x/javadoc-api/index.html?org/springframework/context/support/GenericXmlApplicationContext.html '''<code>GenericXmlApplicationContext</code>''']
 
  +
|
  +
BeanFactory <--+--- ListableBeanFactory ------------+ LifeCycle <-------------+
  +
| | |
  +
+--- HierarchicalBeanFactory --------+ |
  +
+--- ApplicationContext <---- ConfigurableApplicationContext
  +
MessageSource <-------------------------------------+
  +
|
  +
ApplicationEventPublisher <-------------------------+
  +
|
  +
ResourceLoader <---- ResourcePatternResolver <------+
  +
  +
</syntaxhighlight>
  +
  +
{| class='wikitable'
  +
! Interface !! Description !! Methods !! Remarks
  +
|-
  +
| [https://docs.spring.io/spring/docs/5.1.x/javadoc-api/index.html?org/springframework/context/ApplicationContext.html <tt>ApplicationContext</tt>]
  +
| Central interface to provide configuration for an application.
  +
| || read-only while the application is running
  +
|-
  +
| [https://docs.spring.io/spring/docs/5.2.x/javadoc-api/index.html?org/springframework/core/env/EnvironmentCapable.html <tt>EnvironmentCapable</tt>]
  +
| indicating a component that contains and exposes an <tt>Environment</tt> reference.
  +
| <tt>getEnvironment()</tt>
  +
| [https://docs.spring.io/spring/docs/5.2.x/javadoc-api/index.html?org/springframework/core/env/Environment.html <tt>Environment</tt>]
  +
|-
  +
| style='white-space:nowrap' | [https://docs.spring.io/spring/docs/5.2.x/javadoc-api/index.html?org/springframework/beans/factory/ListableBeanFactory.html <tt>ListableBeanFactory</tt>]
  +
| Extension of the BeanFactory interface to be implemented by bean factories that can enumerate all their bean instances, rather than attempting bean lookup by name one by one as requested by clients.
  +
| <tt>getBeanDefinitionNames()</tt>, <tt>getBeanNamesForType()</tt>, <tt>getBeanNamesForAnnotation()</tt> ||
  +
|-
  +
| [https://docs.spring.io/spring/docs/5.2.x/javadoc-api/index.html?org/springframework/context/MessageSource.html <tt>MessageSource</tt>]
  +
| Strategy interface for resolving messages, with support for the parameterization and internationalization of such messages.
  +
| <tt>getMessage()</tt>
  +
| [https://docs.spring.io/spring/docs/5.2.x/javadoc-api/index.html?org/springframework/context/MessageSource.html <tt>ReloadableResourceBundleMessageSource</tt>]
  +
|-
  +
| style='white-space:nowrap' | [https://docs.spring.io/spring/docs/5.2.x/javadoc-api/index.html?org/springframework/core/io/support/ResourcePatternResolver.html <tt>ResourcePatternResolver</tt>]
  +
| Strategy interface for resolving a location pattern (for example, an Ant-style path pattern) into Resource objects.
  +
| <tt>getResources(String pattern)</tt>, <tt>getResource()</tt> ||
  +
|}
  +
  +
* [http://docs.spring.io/spring/docs/4.0.x/javadoc-api/index.html?org/springframework/context/ConfigurableApplicationContext.html '''<tt>ConfigurableApplicationContext</tt>''']
  +
** Prefer <tt>ConfigurableApplicationContext</tt> to <tt>ApplicationContext</tt>
  +
** Pay attention to <tt>registerShutdownHook()</tt> method.
  +
* [http://docs.spring.io/spring/docs/4.0.x/javadoc-api/index.html?org/springframework/context/support/GenericXmlApplicationContext.html '''<tt>GenericXmlApplicationContext</tt>''']
   
 
<syntaxhighlight lang='text' enclose='div' style='margin-left:40px'>
 
<syntaxhighlight lang='text' enclose='div' style='margin-left:40px'>
Line 263: Line 310:
 
* [https://stackoverflow.com/questions/18209237/spring-using-qualifier-with-property-placeholder Spring: Using @Qualifier with Property Placeholder] (Aug 13 '13)
 
* [https://stackoverflow.com/questions/18209237/spring-using-qualifier-with-property-placeholder Spring: Using @Qualifier with Property Placeholder] (Aug 13 '13)
 
** <tt>@Resource(name="${qualifier}")</tt>
 
** <tt>@Resource(name="${qualifier}")</tt>
  +
  +
* [https://docs.spring.io/spring-framework/docs/5.3.x/reference/html/core.html#beans-factory-lifecycle Bean Lifecycle Callbacks]
  +
** Initializing : <tt>@PostConstruct</tt> methods -> <tt>InitializingBean.afterPropertiesSet()</tt> -> <tt>bean@init-method</tt>
  +
** Destroying : <tt>@PreDestroy</tt> methods -> <tt>DisposableBean.destroy()</tt> -> <tt>bean@destroy-method</tt>
   
 
====API====
 
====API====
Line 313: Line 364:
 
| <tt>@Lazy</tt> || || ||
 
| <tt>@Lazy</tt> || || ||
 
|-
 
|-
| style='white-space:nowrap' | <tt>@PostConstruct</tt> || || ||
+
| style='white-space:nowrap' | [https://javaee.github.io/javaee-spec/javadocs/javax/annotation/PostConstruct.html <tt>@PostConstruct</tt>]
  +
| <tt>javax.annotation</tt>
  +
| used on a method that needs to be executed '''after dependency injection''' is done to perform any initialization. ||
 
|-
 
|-
  +
| [https://javaee.github.io/javaee-spec/javadocs/javax/annotation/PreDestroy.html <tt>@PreDestroy</tt>]
| <tt>@PreDestroy</tt> || || ||
 
  +
| <tt>javax.annotation</tt>
  +
| used on a method as a callback notification to signal that the instance is in the process of being removed by the container. ||
 
|-
 
|-
 
| colspan='4' |
 
| colspan='4' |
Line 505: Line 560:
 
| A data structure representing HTTP request or response headers. ||
 
| A data structure representing HTTP request or response headers. ||
 
|-
 
|-
| [http://hc.apache.org/httpcomponents-core-4.4.x/httpcore/apidocs/index.html?org/apache/http/HttpHeaders.html <tt>HttpHeaders</tt>]
+
| [http://hc.apache.org/httpcomponents-core-4.4.x/current/httpcore/apidocs/index.html?org/apache/http/HttpHeaders.html <tt>HttpHeaders</tt>]
 
| <tt>org.apache.http</tt>
 
| <tt>org.apache.http</tt>
 
| Constants enumerating the HTTP headers. || RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), RFC2518 (WebDAV)
 
| Constants enumerating the HTTP headers. || RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), RFC2518 (WebDAV)
Line 554: Line 609:
 
| <tt>o.s.web.bind.annotation</tt>
 
| <tt>o.s.web.bind.annotation</tt>
 
| Annotation which indicates that a method parameter should be bound to a web request parameter.
 
| Annotation which indicates that a method parameter should be bound to a web request parameter.
  +
| since v2.5. In Spring MVC, "request parameters" map to query parameters, form data, and parts in multipart requests.
|
 
 
|-
 
|-
 
| [https://docs.spring.io/spring/docs/5.1.x/javadoc-api/index.html?org/springframework/web/bind/annotation/RequestHeader.html <tt>@RequestHeader</tt>]
 
| [https://docs.spring.io/spring/docs/5.1.x/javadoc-api/index.html?org/springframework/web/bind/annotation/RequestHeader.html <tt>@RequestHeader</tt>]
Line 569: Line 624:
 
| <tt>o.s.web.bind.annotation</tt>
 
| <tt>o.s.web.bind.annotation</tt>
 
| Annotation indicating a method parameter should be bound to the body of the web request.
 
| Annotation indicating a method parameter should be bound to the body of the web request.
  +
| since v3.0
|
 
 
|-
 
|-
  +
| [https://docs.spring.io/spring-framework/docs/5.3.x/javadoc-api/org/springframework/web/bind/annotation/RequestPart.html <tt>@RequestPart</tt>]
| colspan='4'
 
  +
| <tt>o.s.web.bind.annotation</tt>
  +
| Annotation that can be used to associate the part of a "multipart/form-data" request with a method argument.
  +
| since v3.1
  +
|-
  +
| colspan='4' |
 
|-
 
|-
 
| [https://docs.spring.io/spring/docs/5.1.x/javadoc-api/index.html?org/springframework/web/filter/CommonsRequestLoggingFilter.html <tt>CommonsRequestLoggingFilter</tt>]
 
| [https://docs.spring.io/spring/docs/5.1.x/javadoc-api/index.html?org/springframework/web/filter/CommonsRequestLoggingFilter.html <tt>CommonsRequestLoggingFilter</tt>]
Line 795: Line 855:
 
* [https://docs.spring.io/spring-boot/docs/2.0.x/api/ Spring Boot 2.0 API]
 
* [https://docs.spring.io/spring-boot/docs/2.0.x/api/ Spring Boot 2.0 API]
 
* [https://docs.spring.io/spring-boot/docs/2.0.x/actuator-api/html/ Spring Boot 2.0 Actuator Web API]
 
* [https://docs.spring.io/spring-boot/docs/2.0.x/actuator-api/html/ Spring Boot 2.0 Actuator Web API]
* [http://central.maven.org/maven2/org/springframework/boot/spring-boot-starter-parent/2.0.0.RELEASE/spring-boot-starter-parent-2.0.0.RELEASE.pom <tt>org.springframework.boot » spring-boot-starter-parent » 2.0.0 » pom.xml</tt>]
+
* [https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-starter-parent/2.4.2/spring-boot-starter-parent-2.4.2.pom <tt>org.springframework.boot » spring-boot-starter-parent » 2.4.2 » pom.xml</tt>]
* [http://central.maven.org/maven2/org/springframework/boot/spring-boot-dependencies/2.0.0.RELEASE/spring-boot-dependencies-2.0.0.RELEASE.pom <tt>org.springframework.boot » spring-boot-dependencies » 2.0.0 » pom.xml</tt>]
+
* [https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-dependencies/2.4.1/spring-boot-dependencies-2.4.1.pom <tt>org.springframework.boot » spring-boot-dependencies » 2.4.1 » pom.xml</tt>]
 
* [https://docs.spring.io/spring-boot/docs/2.0.x/api/index.html?org/springframework/boot/autoconfigure/SpringBootApplication.html <tt>org.springframework.boot.autoconfigure.SpringBootApplication</tt>]
 
* [https://docs.spring.io/spring-boot/docs/2.0.x/api/index.html?org/springframework/boot/autoconfigure/SpringBootApplication.html <tt>org.springframework.boot.autoconfigure.SpringBootApplication</tt>]
 
** ''a convenience annotation that is equivalent to declaring <tt>@Configuration</tt>, <tt>@EnableAutoConfiguration</tt> and <tt>@ComponentScan</tt>''
 
** ''a convenience annotation that is equivalent to declaring <tt>@Configuration</tt>, <tt>@EnableAutoConfiguration</tt> and <tt>@ComponentScan</tt>''
Line 821: Line 881:
 
===Configuration===
 
===Configuration===
   
  +
* [https://docs.spring.io/spring-boot/docs/2.6.x/reference/html/application-properties.html Common application properties for Spring Boot 2.6]
 
* [https://docs.spring.io/spring-boot/docs/2.1.x/reference/html/common-application-properties.html Common application properties for Spring Boot 2.1]
 
* [https://docs.spring.io/spring-boot/docs/2.1.x/reference/html/common-application-properties.html Common application properties for Spring Boot 2.1]
 
* [https://docs.spring.io/spring-boot/docs/1.5.x/reference/html/common-application-properties.html Common application properties for Spring Boot 1.5]
 
* [https://docs.spring.io/spring-boot/docs/1.5.x/reference/html/common-application-properties.html Common application properties for Spring Boot 1.5]
  +
  +
* [https://docs.spring.io/spring-boot/docs/2.1.x/reference/html/auto-configuration-classes.html Auto-configuration classes in Spring Boot 2.1]
  +
* [https://github.com/spring-projects/spring-boot/blob/2.1.x/spring-boot-project/spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories <tt>spring.factories</tt>]
  +
** list all Auto Configure
   
 
* [http://docs.spring.io/spring-boot/docs/1.5.x/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-auto-configuration Spring MVC auto-configuration]
 
* [http://docs.spring.io/spring-boot/docs/1.5.x/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-auto-configuration Spring MVC auto-configuration]
Line 840: Line 905:
 
** Read a property from <tt>application.properties</tt> file using <tt>@ConfigurationProperties</tt>
 
** Read a property from <tt>application.properties</tt> file using <tt>@ConfigurationProperties</tt>
 
** and reading a property using the <tt>@Value</tt> annotation.
 
** and reading a property using the <tt>@Value</tt> annotation.
  +
  +
* [https://stackoverflow.com/questions/50501382/default-value-for-application-properties-profile-environment-placeholder-canno Default value for application.properties (profile) environment placeholder cannot be comma separated] (May 24 '18)
  +
** <tt>spring.profiles.active=${PROFILES_ACTIVE:'dev,local'}</tt>
  +
  +
* [https://stackabuse.com/the-value-annotation-in-spring/ The @Value Annotation in Spring]
  +
** basic form: <tt>@Value("${car.brand")</tt>
  +
** default valued form: <tt>@Value("${car.type:Sedan}")</tt>
  +
** SpEL form: <tt>@Value("#{systemProperties['user.name']}")</tt>
   
 
====API====
 
====API====
Line 860: Line 933:
   
 
* [http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#production-ready Spring Boot Actuator: Production-ready features]
 
* [http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#production-ready Spring Boot Actuator: Production-ready features]
  +
* [https://docs.spring.io/spring-boot/docs/2.2.x/reference/html/production-ready-features.html#production-ready-endpoints Spring Boot 2.2 Actuator Endpoints]
 
* [https://spring.io/guides/gs/actuator-service/ Building a RESTful Web Service with Spring Boot Actuator]
 
* [https://spring.io/guides/gs/actuator-service/ Building a RESTful Web Service with Spring Boot Actuator]
 
* [https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Migration-Guide#spring-boot-actuator Spring Boot 2.0 Migration Guide / Spring Boot Actuator]
 
* [https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Migration-Guide#spring-boot-actuator Spring Boot 2.0 Migration Guide / Spring Boot Actuator]
Line 865: Line 939:
 
* [https://dzone.com/articles/spring-boot-actuator-a-complete-guide Spring Boot Actuator: A Complete Guide] (Feb. 27, 17)
 
* [https://dzone.com/articles/spring-boot-actuator-a-complete-guide Spring Boot Actuator: A Complete Guide] (Feb. 27, 17)
 
** Securing Actuator Endpoints
 
** Securing Actuator Endpoints
  +
  +
{| class='wikitable'
  +
! Endpoint !! Description !! Remarks
  +
|-
  +
| <tt>beans</tt> || Displays a complete list of all the Spring beans in your application. ||
  +
|-
  +
| <tt>env</tt> || Exposes properties from Spring’s <tt>ConfigurableEnvironment</tt>. ||
  +
|}
  +
  +
* [https://stackoverflow.com/questions/23894010/spring-boot-security-disable-security Spring boot Security Disable security] (May 27 '14)
  +
** <tt>spring.autoconfigure.exclude</tt>
  +
** <tt>security.basic.enabled</tt>, <tt>management.security.enabled</tt> : '''Deprecated''' in Spring Boot 2
  +
  +
* [https://stackoverflow.com/questions/24503790/pretty-print-json-output-of-spring-boot-actuator-endpoints Pretty print JSON output of Spring Boot Actuator endpoints] (Jul 1 '14)
  +
** <tt>spring.jackson.serialization.INDENT_OUTPUT: true</tt>
   
 
===Error Control===
 
===Error Control===
Line 885: Line 974:
 
| ||
 
| ||
 
|}
 
|}
  +
  +
===Logging===
  +
  +
* [https://stackoverflow.com/questions/30118683/how-to-log-sql-statements-in-spring-boot How to log SQL statements in Spring Boot?]
  +
** <tt>logging.level.org.hibernate.SQL=DEBUG</tt>
  +
** <tt>logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE</tt>
  +
** <tt>logging.level.org.hibernate.type=TRACE</tt>
  +
** <tt>spring.jpa.properties.hibernate.show_sql=true</tt>
  +
** <tt>spring.jpa.properties.hibernate.format_sql=true</tt>
  +
** <tt>spring.jpa.properties.hibernate.use_sql_comments=true</tt>
   
 
===REST===
 
===REST===
Line 893: Line 992:
 
* [https://blog.codecentric.de/en/2017/08/parsing-of-localdate-query-parameters-in-spring-boot/ Parsing of LocalDate query parameters in Spring Boot] (08/07/17)
 
* [https://blog.codecentric.de/en/2017/08/parsing-of-localdate-query-parameters-in-spring-boot/ Parsing of LocalDate query parameters in Spring Boot] (08/07/17)
 
* [https://stackoverflow.com/questions/45905039/set-default-format-for-localdatetime-jsr310-in-spring-when-passed-to-a-rest-en Set default format for LocalDateTime (jsr310) in spring when passed to a rest end point] (Aug 27 '17)
 
* [https://stackoverflow.com/questions/45905039/set-default-format-for-localdatetime-jsr310-in-spring-when-passed-to-a-rest-en Set default format for LocalDateTime (jsr310) in spring when passed to a rest end point] (Aug 27 '17)
  +
  +
* [https://stackoverflow.com/questions/49845355/spring-boot-controller-upload-multipart-and-json-to-dto Spring Boot controller - Upload Multipart and JSON to DTO] (Apr 15 '18)
  +
** <syntaxhighlight lang='java' inline class='inline'>@RequestPart("user") @Valid User user, @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file</syntaxhighlight>
  +
* [https://spring.io/guides/gs/uploading-files/ Uploading Files] :
  +
** <syntaxhighlight lang='java' inline class='inline'>@RequestParam("file") MultipartFile file</syntaxhighlight>
  +
  +
===Database===
  +
  +
* [https://docs.spring.io/spring-boot/docs/2.1.0.M1/reference/html/howto-database-initialization.html Database Initialization]
  +
** using JPA, using Hibernate, using Basic SQL Scripts
  +
  +
{| class='wikitable'
  +
! Property !! Type/Values !! Description !! Remarks
  +
|-
  +
| <code>spring.datasource.initialization-mode</code> || <code>always</code>, <code>never</code> || ||
  +
|-
  +
| <code>spring.datasource.continue-on-error</code> || || ||
  +
|-
  +
| <code>spring.sql.init.mode</code> || <code>always</code>, <code>never</code> || ||
  +
|-
  +
| <code>spring.sql.init.continue-on-error</code> || || ||
  +
|-
  +
| <code>spring.jpa.generate-ddl</code> || boolean
  +
| switches the feature on and off and is vendor independent ||
  +
|-
  +
| <code>spring.jpa.hibernate.ddl-auto</code> || <code>none</code>, <code>validate</code>, <code>update</code>, <code>create</code>, <code>create-drop</code>
  +
| a Hibernate feature that controls the behavior in a more fine-grained way ||
  +
|-
  +
| <code>spring.jpa.defer-datasource-initialization</code> || boolean || ||
  +
|}
  +
  +
* [https://www.javadevjournal.com/spring-boot/spring-boot-hikari/ Configuring Hikari Connection Pool with Spring Boot] (December 28, 2022)
  +
* [https://confluence.atlassian.com/bamkb/hikaricp-properties-1087518069.html HikariCP properties]
  +
  +
{| class='wikitable'
  +
! Property || Type/Values || Default !! Description || Remarks
  +
|-
  +
| <code>spring.datasource.hikari.connection-timeout</code> || <code>integer</code> || 2,000
  +
| maximum number of milliseconds that a client will wait for a connection ||
  +
|-
  +
| <code>spring.datasource.hikari.minimum-idle</code> || <code>integer</code> || 10
  +
| minimum number of idle connections maintained by HikariCP in a connection pool ||
  +
|-
  +
| <code>spring.datasource.hikari.maximum-pool-size</code> || <code>integer</code> || 10
  +
| maximum pool size ||
  +
|-
  +
| <code>spring.datasource.hikari.idle-timeout</code> || <code>integer</code> ||
  +
| maximum idle time for connection
  +
|-
  +
| <code>spring.datasource.hikari.max-lifetime</code> || <code>integer</code> ||
  +
| maximum lifetime in milliseconds of a connection in the pool after it is closed.
  +
|-
  +
| <code>spring.datasource.hikari.auto-commit</code> || <code>boolean</code> || <code>true</code>
  +
| default auto-commit behavior ||
  +
|}
   
 
===Test===
 
===Test===
Line 932: Line 1,086:
 
| An enumeration web environment modes
 
| An enumeration web environment modes
 
| <code>DEFINED_PORT</code>, <code>MOCK</code>, <code>NONE</code>, <code>RANDOM_PORT</code>
 
| <code>DEFINED_PORT</code>, <code>MOCK</code>, <code>NONE</code>, <code>RANDOM_PORT</code>
  +
|-
  +
| [https://docs.spring.io/spring-boot/docs/2.0.x/api/index.html?org/springframework/boot/test/context/TestConfiguration.html <tt>@TestConfiguration</tt>]
  +
| <tt>@Configuration</tt> that can be used to define '''additional''' beans or customizations for a test.
  +
| [https://howtodoinjava.com/spring-boot2/testing/springboot-test-configuration/ <tt>@TestConfiguration</tt>]
  +
|-
  +
| [https://docs.spring.io/spring-boot/docs/2.0.x/api/index.html?org/springframework/boot/test/context/SpringBootTest.html <tt>@MockBean</tt>]
  +
| Annotation that can be used to add mocks to a Spring ApplicationContext. ||
 
|-
 
|-
 
| [https://docs.spring.io/spring-boot/docs/2.0.x/api/index.html?org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTest.html <tt>@WebMvcTest</tt>]
 
| [https://docs.spring.io/spring-boot/docs/2.0.x/api/index.html?org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTest.html <tt>@WebMvcTest</tt>]
Line 939: Line 1,100:
 
| Annotation that can be applied to a test class to enable and configure auto-configuration of MockMvc. ||
 
| Annotation that can be applied to a test class to enable and configure auto-configuration of MockMvc. ||
 
|-
 
|-
| [https://docs.spring.io/spring-boot/docs/2.0.x/api/index.html?org/springframework/boot/test/context/SpringBootTest.html <tt>@MockBean</tt>]
+
| [https://docs.spring.io/spring-boot/docs/2.3.x/api/index.html?org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTest.html <tt>@DataJpaTest</tt>]
| Annotation that can be used to add mocks to a Spring ApplicationContext. ||
+
| Annotation for a JPA test that focuses only on JPA components. || <tt>@AutoConfigureTestDatabase</tt>
  +
|-
  +
| [https://docs.spring.io/spring-boot/docs/2.3.x/api/index.html?org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabase.html <tt>@AutoConfigureTestDatabase</tt>]
  +
| Annotation that can be applied to a test class to configure a test database to use instead of any application defined or auto-configured data source. || <tt>AutoConfigureTestDatabase.Replace</tt>
 
|}
 
|}
  +
  +
* [https://howtodoinjava.com/spring-boot2/testing/ Spring Boot Test Tutorials]
   
 
* [https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4 Testing improvements in Spring Boot 1.4] (APRIL 15, 2016)
 
* [https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4 Testing improvements in Spring Boot 1.4] (APRIL 15, 2016)
Line 949: Line 1,115:
 
* [https://docs.spring.io/spring-boot/docs/2.0.x/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests Auto-configured Spring MVC Tests]
 
* [https://docs.spring.io/spring-boot/docs/2.0.x/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests Auto-configured Spring MVC Tests]
 
** ''@WebMvcTest auto-configures the Spring MVC infrastructure and limits scanned beans to <tt>@Controller</tt>, <tt>@ControllerAdvice</tt>, <tt>@JsonComponent</tt>, <tt>Converter</tt>, <tt>GenericConverter</tt>, <tt>Filter</tt>, <tt>WebMvcConfigurer</tt>, and <tt>HandlerMethodArgumentResolver</tt>. Regular <tt>@Component</tt> beans are not scanned when using this annotation.''
 
** ''@WebMvcTest auto-configures the Spring MVC infrastructure and limits scanned beans to <tt>@Controller</tt>, <tt>@ControllerAdvice</tt>, <tt>@JsonComponent</tt>, <tt>Converter</tt>, <tt>GenericConverter</tt>, <tt>Filter</tt>, <tt>WebMvcConfigurer</tt>, and <tt>HandlerMethodArgumentResolver</tt>. Regular <tt>@Component</tt> beans are not scanned when using this annotation.''
  +
  +
* [https://stackoverflow.com/questions/41315386/spring-boot-1-4-datajpatest-error-creating-bean-with-name-datasource Spring Boot 1.4 @DataJpaTest - Error creating bean with name 'dataSource'] (Dec 24 '16)
  +
** <tt>@DataJpaTest @AutoConfigureTestDatabase(replace = NONE)</tt>
  +
  +
* Auto configuration not necessary for unit testing
  +
<syntaxhighlight lang='java' enclose='div'>
  +
@EnableAutoConfiguration(exclude = {
  +
EndpointAutoConfiguration.class, //o.s.b.actuate.autoconfigure.endpoint.EndpointAutoConfiguration
  +
JmxEndpointAutoConfiguration.class,
  +
InfoContributorAutoConfiguration.class,
  +
CompositeMeterRegistryAutoConfiguration.class,
  +
JvmMetricsAutoConfiguration.class,
  +
LogbackMetricsAutoConfiguration.class,
  +
MetricsAutoConfiguration.class,
  +
SystemMetricsAutoConfiguration.class,
  +
SimpleMetricsExportAutoConfiguration.class,
  +
HttpClientMetricsAutoConfiguration.class,
  +
MappingsEndpointAutoConfiguration.class,
  +
ManagementContextAutoConfiguration.class,
  +
ConditionsReportEndpointAutoConfiguration.class,
  +
DataSourceAutoConfiguration.class,
  +
DataSourceTransactionManagerAutoConfiguration.class,
  +
HibernateJpaAutoConfiguration.class,
  +
SecurityAutoConfiguration.class,
  +
OAuth2ClientAutoConfiguration.class,
  +
ReactiveOAuth2ClientAutoConfiguration.class,
  +
OAuth2ResourceServerAutoConfiguration.class,
  +
ReactiveOAuth2ResourceServerAutoConfiguration.class,
  +
FeignAutoConfiguration.class,
  +
TraceWebClientAutoConfiguration.class
  +
})
  +
</syntaxhighlight>
  +
  +
====Test Class Templates====
  +
  +
=====Test class explicitly optimized=====
  +
  +
When testing service or repository classes, to execute the test more quickly, it is desirable not to load unnecessary beans such as MVC beans or actuator configuration beans. The following code sample shows how to do it.
  +
  +
<syntaxhighlight lang='java' enclose='div' style="white-space:nowrap">
  +
  +
@SpringBootTest(
  +
properties = { "management.endpoints.enabled-by-default=false" },
  +
webEnvironment=WebEnvironment.MOCK // NONE, MOCK, ...
  +
)
  +
@EnableAutoConfiguration(exclude = {
  +
EndpointAutoConfiguration.class, //o.s.b.actuate.autoconfigure.endpoint.EndpointAutoConfiguration
  +
WebEndpointAutoConfiguration.class,
  +
JmxEndpointAutoConfiguration.class, //o.s.b.actuate.autoconfigure.endpoint.jmx.JmxEndpointAutoConfiguration
  +
MappingsEndpointAutoConfiguration.class, //o.s.b.actuate.autoconfigure.web.mappings.MappingsEndpointAutoConfiguration
  +
CompositeMeterRegistryAutoConfiguration.class, //o.s.b.actuate.autoconfigure.metrics.CompositeMeterRegistryAutoConfiguration
  +
MetricsAutoConfiguration.class, //o.s.b.actuate.autoconfigure.metrics.MetricsAutoConfiguration
  +
JvmMetricsAutoConfiguration.class, //o.s.b.actuate.autoconfigure.metrics.JvmMetricsAutoConfiguration
  +
SystemMetricsAutoConfiguration.class, //o.s.b.actuate.autoconfigure.metrics.SystemMetricsAutoConfiguration
  +
LogbackMetricsAutoConfiguration.class, //o.s.b.actuate.autoconfigure.metrics.LogbackMetricsAutoConfiguration
  +
HttpClientMetricsAutoConfiguration.class, //o.s.b.actuate.autoconfigure.metrics.web.client.HttpClientMetricsAutoConfiguration
  +
SimpleMetricsExportAutoConfiguration.class, //o.s.b.actuate.autoconfigure.metrics.export.simple.SimpleMetricsExportAutoConfiguration
  +
ManagementContextAutoConfiguration.class, //o.s.b.actuate.autoconfigure.web.server.ManagementContextAutoConfiguration
  +
ServletManagementContextAutoConfiguration.class,
  +
ConditionsReportEndpointAutoConfiguration.class, //o.s.b.actuate.autoconfigure.condition.ConditionsReportEndpointAutoConfiguration
  +
InfoContributorAutoConfiguration.class, //o.s.b.actuate.autoconfigure.info.InfoContributorAutoConfiguration
  +
HealthContributorAutoConfiguration.class,
  +
DiskSpaceHealthContributorAutoConfiguration.class,
  +
DataSourceAutoConfiguration.class, //o.s.b.autoconfigure.jdbc.DataSourceAutoConfiguration
  +
DataSourceTransactionManagerAutoConfiguration.class, //o.s.b.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
  +
HibernateJpaAutoConfiguration.class, //o.s.b.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
  +
SecurityAutoConfiguration.class, //o.s.b.autoconfigure.security.servlet.SecurityAutoConfiguration
  +
OAuth2ClientAutoConfiguration.class, //o.s.b.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration
  +
ReactiveOAuth2ClientAutoConfiguration.class, //o.s.b.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration
  +
OAuth2ResourceServerAutoConfiguration.class, //o.s.b.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration
  +
ReactiveOAuth2ResourceServerAutoConfiguration.class, //o.s.b.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration
  +
FeignAutoConfiguration.class, //o.s.cloud.openfeign.FeignAutoConfiguration
  +
TraceWebClientAutoConfiguration.class //o.s.cloud.sleuth.instrument.web.client.TraceWebClientAutoConfiguration
  +
})
  +
@TestInstance(Lifecycle.PER_CLASS)
  +
public class ApplicationInOptimalTest{
  +
  +
private Logger logger = LoggerFactory.getLogger(this.getClass());
  +
  +
// Define additional beans or customizations for a test.
  +
// Automatically loaded by @SpringBootTest without 'classes' property
  +
@TestConfiguration
  +
static class ExtraConfig{
  +
  +
@Bean
  +
public CatalogService testCatalogService(){
  +
...
  +
}
  +
}
  +
  +
@Autowired
  +
private ApplicationContext springContext;
  +
  +
@Autowired
  +
private OrderService orderService;
  +
  +
@Autowired
  +
private CatalogService catalogService;
  +
  +
@Test
  +
public void testGetBeanDefinitionNames() {
  +
  +
final int cnt = springContext.getBeanDefinitionCount();
  +
final String[] names = springContext.getBeanDefinitionNames();
  +
Arrays.sort(names);
  +
  +
this.logger.info("Defined Beans : {}", cnt);
  +
for(String name: names) this.logger.info(" - {}", name);
  +
  +
Assertions.assertTrue(cnt > 0, "The Spring container has no bean which makes no sense.");
  +
Assertions.assertTrue(Arrays.binarySearch(names, "web3j") > -1, "The Spring container doesn't contain 'web3j' bean, which is never expected.");
  +
Assertions.assertTrue(Arrays.binarySearch(names, "mvcViewResolver") < 0, "The Spring container still contains 'mvcViewResolver' bean, which is not expected.");
  +
}
  +
  +
@Test
  +
public void testGetConfigurations() {
  +
  +
final Map<String, Object> configs = springContext.getBeansWithAnnotation(Configuration.class);
  +
final int cnt = configs.size();
  +
  +
this.logger.info("Configurations : {}", cnt);
  +
configs.forEach((k, v) -> this.logger.info(" - {} : {}", k, v));
  +
  +
Assertions.assertTrue(cnt > 0, "The Spring container has no configuration, which is impossible.");
  +
}
  +
}
  +
</syntaxhighlight>
  +
  +
=====Test class for literally unit test=====
  +
  +
It is possible to auto-wire test-purpose bean instead of a bean in normal(non-test) Spring Boot configuration (like <tt>EthereumClientConfig</tt> in below example) by defining <tt>@Primary</tt> bean in the extra configuration imported only by test.
  +
  +
<syntaxhighlight lang='java' enclose='div' highlight='1-4, 6, 14-15, 19-20'>
  +
  +
@SpringBootTest(
  +
classes = {IdentityManagerContractServiceImpl.class, EthereumClientConfig.class},
  +
properties = {"management.endpoints.enabled-by-default=false", "security=", "spring.security.enabled=false"},
  +
webEnvironment = WebEnvironment.NONE)
  +
@TestInstance(Lifecycle.PER_CLASS)
  +
@Import(IdentityManagerContractServiceImplTest.ExtraConfig.class)
  +
class IdentityManagerContractServiceImplTest{
  +
  +
final private Logger logger = LoggerFactory.getLogger(this.getClass());
  +
  +
// Define additional beans or customizations for a test.
  +
// NOT loaded automatically by @SpringBootTest with 'classes' property
  +
// Use '@Import' to load explicitly
  +
@TestConfiguration
  +
static class ExtraConfig{
  +
...
  +
  +
// Make another bean instead of a bean in normal configuration to be autowired using @Primary annotation.
  +
@Bean @Primary
  +
SendTxProcessor sendTxProcessorWithoutRetry(){
  +
...
  +
}
  +
}
  +
  +
@SpyBean
  +
private TestSpecialAccountServiceImpl specialAccountSrv;
  +
  +
@Autowired
  +
private IdentityManagerContractService identityManagerContract;
  +
  +
...
  +
  +
}
  +
  +
</syntaxhighlight>
  +
  +
=====Test class for concurrency behavior=====
  +
  +
To test a method in concurrent executions, apply parallel execution(<tt>@Execution(CONCURRENT)</tt>) and repeated test(<tt>@RepeatedTest</tt>) together. The life-cycle of the test instance is expected to be <tt>PER_METHOD</tt>.
  +
  +
<syntaxhighlight lang='java' enclose='div' highlight='6-7, 32-34'>
  +
  +
@SpringBootTest(
  +
classes = {SafeTokenContractServiceImpl.class, EthereumClientConfig.class},
  +
properties = {"management.endpoints.enabled-by-default=false", "security=", "spring.security.enabled=false"},
  +
webEnvironment = WebEnvironment.NONE)
  +
@Import(SafeTokenContractServiceImplConcurrentTest.ExtraConfig.class)
  +
@TestInstance(Lifecycle.PER_METHOD)
  +
@Execution(ExecutionMode.CONCURRENT)
  +
public class SafeTokenContractServiceImplConcurrentTest{
  +
  +
final private Logger logger = LoggerFactory.getLogger(this.getClass());
  +
  +
@TestConfiguration
  +
static class ExtraConfig{
  +
  +
@Bean
  +
public AccountService testAccountService() throws Exception {
  +
...
  +
}
  +
  +
...
  +
}
  +
  +
@Value("${smart-contracts.safe-token.address}")
  +
private String tokenAddress;
  +
  +
@Autowired
  +
private AccountService accountSrv;
  +
  +
@Autowired
  +
private SafeTokenContractServiceImpl tokenContractSrv;
  +
  +
@RepeatedTest(10)
  +
@Execution(ExecutionMode.CONCURRENT)
  +
public void testMint() {
  +
...
  +
try {
  +
this.tokenContractSrv.mint(from, to, amt);
  +
}catch(Exception ex) {
  +
this.logger.error("Fail to execute `mint`", ex);
  +
throw ex;
  +
}
  +
}
  +
  +
</syntaxhighlight>
  +
  +
For the above test case to run correctly not affecting other test cases that has no <tt>@EXECUTION(CONCURRENT)</tt>, following is proper for JUnit Platform configuration file(<tt>junit-platform.properties</tt>).
  +
  +
<syntaxhighlight lang='properties' enclose='div' highlight='0'>
  +
! https://junit.org/junit5/docs/current/user-guide/#running-tests-config-params
  +
! https://junit.org/junit5/docs/current/user-guide/#writing-tests-parallel-execution
  +
  +
junit.jupiter.testinstance.lifecycle.default = per_class
  +
junit.jupiter.execution.parallel.enabled = true
  +
# junit.jupiter.execution.parallel.mode.default = concurrent
  +
# junit.jupiter.execution.parallel.mode.classes.default = concurrent
  +
  +
</syntaxhighlight>
  +
  +
=====Test class for only JPA repositories=====
  +
  +
<syntaxhighlight lang='java' enclose='div' highlight='1, 2'>
  +
  +
@DataJpaTest
  +
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
  +
@TestInstance(Lifecycle.PER_CLASS)
  +
class SpecialAccountRepositoryTest{
  +
  +
final private Logger logger = LoggerFactory.getLogger(this.getClass());
  +
  +
@Autowired
  +
private SpecialAccountRepository specialAccountRepos;
  +
  +
...
  +
  +
}
  +
  +
</syntaxhighlight>
   
 
===misc===
 
===misc===
Line 1,066: Line 1,485:
 
* [http://docs.spring.io/spring-session/docs/1.3.0.RELEASE/reference/html5/ Spring Session 1.3.0 Reference]
 
* [http://docs.spring.io/spring-session/docs/1.3.0.RELEASE/reference/html5/ Spring Session 1.3.0 Reference]
 
* [http://docs.spring.io/spring-session/docs/1.3.0.RELEASE/api/ Spring Session 1.3.0 API]
 
* [http://docs.spring.io/spring-session/docs/1.3.0.RELEASE/api/ Spring Session 1.3.0 API]
  +
  +
==Spring Integration==
  +
  +
* [https://docs.spring.io/spring-integration/docs/ Spring Integration Documentations]
  +
  +
* [https://docs.spring.io/spring-integration/docs/5.2.x/api/ Spring Integration 5.2 API]
   
 
==Spring Data==
 
==Spring Data==
  +
  +
* Projects
  +
{| class='wikitable'
  +
! Project !! Description !! Documentation !! API !! Remarks
  +
|-
  +
| style='white-space:nowrap' | [https://github.com/spring-projects/spring-data-commons Spring Data Commons]
  +
| part of the umbrella Spring Data project that provides shared infrastructure across the Spring Data projects and contains technology neutral repository interfaces as well as a '''metadata model''' for persisting Java classes.
  +
| [https://docs.spring.io/spring-data/commons/docs/current/reference/html/#reference Spring Data Commons Reference] || ||
  +
|}
  +
  +
* Common Annotations
  +
{| class='wikitable'
  +
! Annotation !! Description !! Remarks
  +
|-
  +
| [https://docs.spring.io/spring-data/commons/docs/2.1.x/api/org/springframework/data/annotation/Id.html <tt>@Id</tt>]
  +
| Demarcates an identifier. ||
  +
|-
  +
| [https://docs.spring.io/spring-data/commons/docs/2.1.x/api/org/springframework/data/annotation/AccessType.html <tt>@AccessType</tt>]
  +
| Define how Spring Data shall access values of persistent properties. || <tt>Type.FIELD</tt> <nowiki>|</nowiki> <tt>TYPE.PROPERTY</tt>
  +
|}
   
 
===Spring Data JPA===
 
===Spring Data JPA===
   
 
* [https://stackoverflow.com/questions/26795436/spring-jparepository-detach-and-attach-entity Spring JpaRepository - Detach and Attach entity](Nov 7 '14)
 
* [https://stackoverflow.com/questions/26795436/spring-jparepository-detach-and-attach-entity Spring JpaRepository - Detach and Attach entity](Nov 7 '14)
  +
  +
* [https://www.techferry.com/articles/hibernate-jpa-annotations.html#Column JPA Annotations]
  +
* [https://javaee.github.io/javaee-spec/javadocs/javax/persistence/package-summary.html <code>javax.persistence</code> package]
  +
** <code>@Entity</code>, <code>@Table</code>, <code>@Column</code>, <code>@Id</code>, <code>@IdClass</code>, <code>@Transient</code>, <code>@Temporal</code>, <code>@ForeignKey</code>, <code>@Index</code>, <code>@UniqueConstraint</code>, <code>@OneToOne</code>, <code>@OneToMany</code>, <code>@ManyToOne</code>, <code>@ManyToMany</code>, <code>@JoinColumn</code>, <code>@JoinTable</code>, <code>@Inheritance</code>, <code>@DiscriminatorColumn</code>, <code>@DiscriminatorValue</code>
  +
  +
{| class='wikitable'
  +
! Annotation !! Description !! Remarks
  +
|-
  +
| [https://javaee.github.io/javaee-spec/javadocs/javax/persistence/Entity.html <code>@Entity</code>]
  +
| Specifies that the class is an entity ||
  +
|-
  +
| [https://javaee.github.io/javaee-spec/javadocs/javax/persistence/Table.html <code>@Table</code>]
  +
| Specifies the primary table for the annotated entity
  +
| <code>name</code>, <code>catalog</code>
  +
|-
  +
| [https://javaee.github.io/javaee-spec/javadocs/javax/persistence/Column.html <code>@Column</code>]
  +
| Specifies the mapped column for a persistent property or field
  +
| <code>name</code>, <code>columnDefinition</code>, <code>nullable</code>, <code>unique</code>, <code>length</code>, <code>precision</code>, <code>scale</code>
  +
|-
  +
| [https://javaee.github.io/javaee-spec/javadocs/javax/persistence/Id.html <code>@Id</code>]
  +
| Specifies the primary key of an entity ||
  +
|-
  +
| [https://javaee.github.io/javaee-spec/javadocs/javax/persistence/IdClass.html <code>@IdClass</code>]
  +
| Specifies a composite primary key class that is mapped to multiple fields or properties of the entity ||
  +
|-
  +
| [https://javaee.github.io/javaee-spec/javadocs/javax/persistence/Transient.html <code>@Transient</code>]
  +
| Specifies that the property or field is not persistent ||
  +
|-
  +
| [https://javaee.github.io/javaee-spec/javadocs/javax/persistence/Temporal.html <code>@Temporal</code>]
  +
| Specified for persistent fields or properties of type <tt>java.util.Date</tt> and <tt>java.util.Calendar</tt> ||
  +
|-
  +
| [https://javaee.github.io/javaee-spec/javadocs/javax/persistence/ForeignKey.html <code>@ForeignKey</code>]
  +
| Used to specify the handling of foreign key constraints when schema generation is in effect ||
  +
|-
  +
| [https://javaee.github.io/javaee-spec/javadocs/javax/persistence/Index.html <code>@Index</code>]
  +
| Used in schema generation to specify creation of an index ||
  +
|-
  +
| [https://javaee.github.io/javaee-spec/javadocs/javax/persistence/UniqueConstraint.html <code>@UniqueConstraint</code>]
  +
| Specifies that a unique constraint is to be included in the generated DDL for a primary or secondary table ||
  +
|}
  +
  +
===Spring Data MongoDB===
  +
  +
* [https://docs.spring.io/spring-data/mongodb/docs/3.2.x/reference/html/ Spring Data MongoDB 3.2 Reference]
  +
* [https://docs.spring.io/spring-data/mongodb/docs/3.2.x/api/ Spring Data MongoDB 3.2 API]
  +
  +
* [https://docs.spring.io/spring-data/mongodb/docs/3.2.x/reference/html/#mapping-chapter Mapping]
  +
  +
* [https://mongodb.github.io/mongo-java-driver/4.2/driver/getting-started/quick-start/ MongoDB Driver Quick Start]
  +
* [https://spring.io/guides/gs/accessing-data-mongodb/ Accessing Data with MongoDB]
  +
  +
====Core Classes====
  +
  +
{| class='wikitable'
  +
! Class !! Description !! Source !! Remarks
  +
|-
  +
| style='white-space:nowrap' | [https://docs.spring.io/spring-data/mongodb/docs/3.2.x/api/index.html?org/springframework/data/mongodb/config/AbstractMongoClientConfiguration.html <tt>AbstractMongoClientConfiguration</tt>]
  +
| Base class for Spring Data MongoDB configuration using JavaConfig with <tt>MongoClient</tt>.
  +
| style='white-space:nowrap' | [https://github.com/spring-projects/spring-data-mongodb/blob/3.1.3/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/AbstractMongoClientConfiguration.java <tt>AbstractMongoClientConfiguration.java@3.1.3</tt>] ||
  +
|-
  +
| [https://docs.spring.io/spring-data/mongodb/docs/3.2.x/api/org/springframework/data/mongodb/core/MongoJsonSchemaCreator.html <tt>MongoJsonSchemaCreator</tt>]
  +
| Extracts the MongoJsonSchema for a given Class by applying the following mapping rules. || || factory method
  +
|}
  +
  +
{| class='wikitable'
  +
! Annotation !! Description !! Source !! Remarks
  +
|-
  +
| [https://docs.spring.io/spring-data/mongodb/docs/3.2.x/api/org/springframework/data/mongodb/core/mapping/Document.html <tt>@Document</tt>]
  +
| Identifies a domain object to be persisted to MongoDB. || ||
  +
|-
  +
| [https://docs.spring.io/spring-data/mongodb/docs/3.2.x/api/org/springframework/data/mongodb/core/mapping/Field.html <tt>@Field</tt>]
  +
| Annotation to define custom metadata for document fields. || ||
  +
|-
  +
| [https://docs.spring.io/spring-data/mongodb/docs/3.2.x/api/org/springframework/data/mongodb/core/index/Indexed.html <tt>@Indexed</tt>]
  +
| Mark a field to be indexed using MongoDB's indexing feature. || ||
  +
|}
  +
  +
====Readings====
  +
  +
* [https://docs.spring.io/spring-data/mongodb/docs/3.2.x/reference/html/#mapping.property-population Spring Data MongoDB Property Population]
  +
*# ''If the property is immutable but exposes a with… method, we use the with… method to create a new entity instance with the new property value.''
  +
*# ''If property access (i.e. access through getters and setters) is defined, we’re invoking the setter method.''
  +
*# ''If the property is mutable we set the field directly.''
  +
*# ''If the property is immutable we’re using the constructor to be used by persistence operation to create a copy of the instance.''
  +
** ''By default, we set the field value directly.''
  +
  +
* [https://docs.spring.io/spring-data/mongodb/docs/3.2.x/reference/html/#mongo.jsonSchema.generated Generating document schema from domain object]
  +
** <tt>org.springframework.data.mongodb.core.MongoJsonSchemaCreator</tt>
  +
  +
* [https://docs.spring.io/spring-data/mongodb/docs/3.2.x/reference/html/#repositories.nullability.annotations Nullability Annotations]
  +
  +
====Typical Code Samples====
  +
  +
=====Typical configuration bean=====
  +
  +
<syntaxhighlight lang='java' enclose='div'>
  +
/**
  +
* @author 3rdstage
  +
*
  +
* @see <tt><a href='https://github.com/spring-projects/spring-data-mongodb/blob/3.1.3/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/AbstractMongoClientConfiguration.java'>AbstractMongoClientConfiguration.java</a></tt>
  +
*/
  +
@Configuration
  +
@EnableMongoRepositories
  +
public class MongoClientConfig extends AbstractMongoClientConfiguration{
  +
  +
  final private Logger logger = LoggerFactory.getLogger(this.getClass());
  +
  +
@Bean
  +
@Override
  +
public MongoClient mongoClient() {
  +
return super.mongoClient();
  +
}
  +
  +
  @Override
  +
  protected String getDatabaseName() {
  +
    return "eth";
  +
  }
  +
  +
  @Override
  +
  protected String getMappingBasePackage() {
  +
    return "thirdstage.eth.disassembly.repos";
  +
  }
  +
  +
 @Override
  +
  public boolean autoIndexCreation() {
  +
    return true;
  +
  }
  +
  +
  // https://docs.spring.io/spring-data/mongodb/docs/3.2.x/reference/html/#mongo.custom-converters.xml
  +
  @Override
  +
  protected void configureConverters(MongoConverterConfigurationAdapter adapter) {
  +
    super.configureConverters(adapter);
  +
    //adapter.registerConverter(new EpochTimeToDateConverter());
  +
    //adapter.registerConverter(new EpochTimeFromDateConverter());
  +
  }
  +
  +
  @Bean
  +
  public MongoClientSettingsBuilderCustomizer customizer() {
  +
    return (builder) -> {
  +
      List<Convention> cvns = Conventions.DEFAULT_CONVENTIONS;
  +
      //cvns.add(Conventions.SET_PRIVATE_FIELDS_CONVENTION);
  +
      CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(
  +
        MongoClientSettings.getDefaultCodecRegistry(),
  +
        CodecRegistries.fromProviders(
  +
            PojoCodecProvider.builder()
  +
              .automatic(true)
  +
              .conventions(cvns)
  +
              .build()));
  +
      builder.codecRegistry(pojoCodecRegistry);
  +
    };
  +
  }
  +
}
  +
</syntaxhighlight>
  +
  +
=====Domain Object with custom type conversion using converted typed getter/setter without global type converter=====
  +
  +
<syntaxhighlight lang='java' enclose='div'>
  +
@Getter
  +
@Setter
  +
@RequiredArgsConstructor
  +
@Accessors(chain = true)
  +
@Document(collection = "transactions")
  +
public class Transaction implements java.io.Serializable{
  +
  +
@Id
  +
private final String hash;
  +
  +
@Field(name = "block_no")
  +
private long blockNo;
  +
  +
private long index;
  +
  +
private String from;
  +
  +
// denormalized field from account
  +
@Field("from_is_contr")
  +
private boolean fromIsContract;
  +
  +
private String to;
  +
  +
// denormalized field from account
  +
@Field("to_is_contr")
  +
private boolean toIsContract;
  +
  +
@Getter(AccessLevel.NONE)
  +
@Setter(AccessLevel.NONE)
  +
@AccessType(AccessType.Type.FIELD)
  +
@Field(targetType = DECIMAL128)
  +
private BigDecimal value;
  +
  +
public BigInteger getValue() {
  +
return this.value.toBigInteger();
  +
}
  +
  +
public Transaction setValue(BigInteger val) {
  +
this.value = new BigDecimal(val);
  +
return this;
  +
}
  +
  +
@Indexed
  +
private Instant at;
  +
  +
}
  +
</syntaxhighlight>
   
 
===Spring Data Redis===
 
===Spring Data Redis===
Line 1,081: Line 1,730:
   
 
* [http://www.kennybastani.com/2015/07/spring-cloud-docker-microservices.html Building Microservices with Spring Cloud and Docker] (July 12, 2015)
 
* [http://www.kennybastani.com/2015/07/spring-cloud-docker-microservices.html Building Microservices with Spring Cloud and Docker] (July 12, 2015)
  +
  +
===Spring Cloud OpenFeign===
  +
  +
* https://spring.io/projects/spring-cloud-openfeign
  +
* Desc. : provides OpenFeign integrations for Spring Boot apps through autoconfiguration and binding to the Spring Environment and other Spring programming model idioms.
  +
* Sources :
  +
* Maven artifacts : [https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign <tt>org.springframework.cloud » spring-cloud-starter-openfeign</tt>]
  +
  +
{| class='wikitable'
  +
! Version !! Documentation !! API !! Remarks
  +
|-
  +
| 3.1 || [https://docs.spring.io/spring-cloud-openfeign/docs/3.1.x/reference/html/ Spring Cloud OpenFeign 3.1.0 Reference]
  +
| [https://javadoc.io/doc/org.springframework.cloud/spring-cloud-openfeign-core/3.1.0/index.html Spring Cloud OpenFeign Core 3.1.0 API] ||
  +
|}
   
 
==misc==
 
==misc==
Line 1,096: Line 1,759:
 
| '''<tt>context</tt>''' || style='white-space:nowrap' | <tt>http://www.springframework.org/schema/context</tt>
 
| '''<tt>context</tt>''' || style='white-space:nowrap' | <tt>http://www.springframework.org/schema/context</tt>
 
| Defines the configuration elements for the Spring Framework's application.
 
| Defines the configuration elements for the Spring Framework's application.
| [https://github.com/spring-projects/spring-framework/tree/master/spring-context/src/main/resources/org/springframework/context/config <tt>org.springframework.context.config</tt>]
+
| style='white-space:nowrap' | [https://github.com/spring-projects/spring-framework/tree/master/spring-context/src/main/resources/org/springframework/context/config <tt>org.springframework.context.config</tt>]
 
[https://github.com/spring-projects/spring-framework/blob/v4.2.4.RELEASE/spring-context/src/main/resources/org/springframework/context/config/spring-context-4.0.xsd <tt>spring-context-4.0.xsd</tt>]
 
[https://github.com/spring-projects/spring-framework/blob/v4.2.4.RELEASE/spring-context/src/main/resources/org/springframework/context/config/spring-context-4.0.xsd <tt>spring-context-4.0.xsd</tt>]
|-
 
 
|-
 
|-
 
| '''<tt>aop</tt>''' || style='white-space:nowrap' | <tt>http://www.springframework.org/schema/aop</tt>
 
| '''<tt>aop</tt>''' || style='white-space:nowrap' | <tt>http://www.springframework.org/schema/aop</tt>
Line 1,104: Line 1,766:
 
| [https://github.com/spring-projects/spring-framework/tree/master/spring-aop/src/main/resources/org/springframework/aop/config <tt>org.springframework.aop.config</tt>]
 
| [https://github.com/spring-projects/spring-framework/tree/master/spring-aop/src/main/resources/org/springframework/aop/config <tt>org.springframework.aop.config</tt>]
 
[https://github.com/spring-projects/spring-framework/blob/v4.2.4.RELEASE/spring-aop/src/main/resources/org/springframework/aop/config/spring-aop-4.0.xsd <tt>spring-aop-4.0.xsd</tt>]
 
[https://github.com/spring-projects/spring-framework/blob/v4.2.4.RELEASE/spring-aop/src/main/resources/org/springframework/aop/config/spring-aop-4.0.xsd <tt>spring-aop-4.0.xsd</tt>]
  +
|-
  +
| '''<tt>jdbc</tt>''' || style='white-space:nowrap' | <tt>http://www.springframework.org/schema/jdbc</tt>
  +
| Defines the configuration elements for the Spring Framework's embedded database support.
  +
| style='white-space:nowrap' | [https://github.com/spring-projects/spring-framework/tree/master/spring-jdbc/src/main/resources/org/springframework/jdbc/config <tt>org.springframework.jdbc.config</tt>]
  +
[https://github.com/spring-projects/spring-framework/blob/v4.2.4.RELEASE/spring-jdbc/src/main/resources/org/springframework/jdbc/config/spring-jdbc-4.0.xsd <tt>spring-jdbc-4.0.xsd</tt>]
  +
|-
  +
| '''<tt>tx</tt>''' || style='white-space:nowrap' | <tt>http://www.springframework.org/schema/tx</tt>
  +
| Defines the elements used in the Spring Framework's declarative transaction management infrastructure.
  +
| [http://www.springframework.org/schema/tx/spring-tx-3.0.xsd <tt>spring-tx-3.0.xsd</tt>]
  +
|-
  +
| '''<tt>mvc</tt>''' || style='white-space:nowrap' | <tt>http://www.springframework.org/schema/mvc</tt>
  +
|
  +
| [http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd <tt>spring-mvc-3.0.xsd</tt>]
  +
|-
  +
| '''<tt>util</tt>''' || style='white-space:nowrap' | <tt>http://www.springframework.org/schema/util</tt>
  +
|
  +
| [https://github.com/spring-projects/spring-framework/blob/v4.2.4.RELEASE/spring-beans/src/main/resources/org/springframework/beans/factory/xml/spring-util-4.0.xsd <tt>spring-util-4.0.xsd</tt>]
  +
|-
  +
| '''<tt>task</tt>''' || style='white-space:nowrap' | <tt>http://www.springframework.org/schema/task/</tt>
  +
|
  +
| [http://www.springframework.org/schema/task/spring-task-4.2.xsd <tt>spring-task-4.2.xsd</tt>]
 
|}
 
|}
 
</div>
 
</div>
   
  +
===Projects===
* '''<code>beans</code>'''
 
** namespace : <code>http://www.springframework.org/schema/beans</code>
 
** description : defines the elements to define beans.
 
** sources
 
*** [https://github.com/spring-projects/spring-framework/blob/v4.2.4.RELEASE/spring-beans/src/main/resources/org/springframework/beans/factory/xml/spring-beans-4.0.xsd <code>http://www.springframework.org/schema/beans/spring-beans-4.0.xsd</code>]
 
 
* '''<code>context</code>'''
 
** namespace : <code>http://www.springframework.org/schema/context</code>
 
** description : defines the configuration elements for the Spring Framework's application.
 
** sources
 
*** [https://github.com/spring-projects/spring-framework/tree/master/spring-context/src/main/resources/org/springframework/context/config <code>org.springframework.context.config</code>]
 
*** [https://github.com/spring-projects/spring-framework/blob/v4.2.4.RELEASE/spring-context/src/main/resources/org/springframework/context/config/spring-context-4.0.xsd <code>http://www.springframework.org/schema/context/spring-context-4.0.xsd</code>]
 
 
* '''<code>aop</code>'''
 
** namespace : <code>http://www.springframework.org/schema/aop</code>
 
** description : defines the configuration elements for the Spring Framework's AOP support.
 
** sources
 
*** [https://github.com/spring-projects/spring-framework/tree/master/spring-aop/src/main/resources/org/springframework/aop/config <code>org.springframework.aop.config</code>]
 
*** [https://github.com/spring-projects/spring-framework/blob/v4.2.4.RELEASE/spring-aop/src/main/resources/org/springframework/aop/config/spring-aop-4.0.xsd <code>http://www.springframework.org/schema/aop/spring-aop-4.0.xsd</code>]
 
 
* '''<code>jdbc</code>'''
 
** namespace : <code>http://www.springframework.org/schema/jdbc</code>
 
** description : defines the configuration elements for the Spring Framework's embedded database support.
 
** sources
 
*** [https://github.com/spring-projects/spring-framework/tree/master/spring-jdbc/src/main/resources/org/springframework/jdbc/config <code>org.springframework.jdbc.config</code>]
 
*** [https://github.com/spring-projects/spring-framework/blob/v4.2.4.RELEASE/spring-jdbc/src/main/resources/org/springframework/jdbc/config/spring-jdbc-4.0.xsd <code>http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd</code>]
 
 
* '''<code>tx</code>'''
 
** namespace : http://www.springframework.org/schema/tx
 
** description : defines the elements used in the Spring Framework's declarative transaction management infrastructure.
 
** schema : http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
 
   
  +
====Spring Retry====
* '''<code>mvc</code>'''
 
** namespace : http://www.springframework.org/schema/mvc
 
** description
 
** schema : http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 
   
  +
* https://github.com/spring-projects/spring-retry Spring Retry]
* '''<code>util</code>'''
 
  +
* Desc. : provides declarative retry support for Spring applications.
** namespace : http://www.springframework.org/schema/util
 
** description
 
** sources
 
*** [https://github.com/spring-projects/spring-framework/blob/v4.2.4.RELEASE/spring-beans/src/main/resources/org/springframework/beans/factory/xml/spring-util-4.0.xsd http://www.springframework.org/schema/util/spring-util-4.0.xsd]
 
 
* '''<code>task</code>'''
 
** namespace : http://www.springframework.org/schema/task/
 
** description
 
** schema : http://www.springframework.org/schema/task/spring-task-4.2.xsd
 
   
 
===Samples===
 
===Samples===
Line 1,160: Line 1,802:
   
 
<syntaxhighlight lang='yaml' enclose='div' style='margin-left:40px'>
 
<syntaxhighlight lang='yaml' enclose='div' style='margin-left:40px'>
# https://docs.spring.io/spring-boot/docs/2.2.x/reference/html/common-application-properties.html
+
# https://docs.spring.io/spring-boot/docs/2.2.x/reference/html/appendix-application-properties.html
   
debug: false
+
debug: !!bool ${SPRING_DEBUG:false}
trace: false
+
trace: !!bool ${SPRING_TRACE:false}
   
 
logging.level:
 
logging.level:
org.springframework.boot.autoconfigure: ERROR
+
org.springframework: INFO
  +
org.springframework.boot.autoconfigure: WARN
  +
org.apache.tomcat: INFO
  +
org.apache.catalina: INFO
  +
org.eclipse.jetty: INFO
  +
org.hibernate.SQL: WARN
  +
org.hibernate.type: WARN
  +
org.hibernate.tool.hbm2ddl: TRACE
   
 
server:
 
server:
Line 1,175: Line 1,824:
   
 
spring:
 
spring:
application.name: ChainZ Donation Service Smart Contract PoC
+
application.name: foo-bar
 
profiles:
 
profiles:
 
active: local
 
active: local
Line 1,186: Line 1,835:
 
max-file-size: 100MB
 
max-file-size: 100MB
 
max-request-size: 100MB
 
max-request-size: 100MB
  +
  +
spring.aop:
  +
auto: true # Add @EnableAspectJAutoProxy.
  +
proxy-target-class: true # Whether subclass-based (CGLIB) proxies are to be created (true), as opposed to standard Java interface-based proxies (false).
   
 
spring.security:
 
spring.security:
Line 1,191: Line 1,844:
 
name: boot
 
name: boot
 
password: boot
 
password: boot
  +
  +
springdoc:
  +
use-fqn: false
  +
swagger-ui:
  +
show-common-extensions: true
  +
default-model-rendering: "example" # ("example" | "model")
  +
default-models-expand-depth: 5
  +
default-model-expand-depth: 5
  +
disable-swagger-default-url: false
  +
#validator-url: 'none' # 'none' : no validation
  +
api-docs:
  +
path: /swagger-ui/api-docs
  +
enabled: true
  +
 
---
 
---
  +
spring.profiles: local
  +
  +
debug: !!bool ${SPRING_DEBUG:true}
  +
trace: !!bool ${SPRING_TRACE:false}
  +
  +
logging.level:
  +
org.hibernate.SQL: DEBUG
  +
org.hibernate.type: TRACE
  +
# https://cloud.spring.io/spring-cloud-static/spring-cloud-openfeign/2.2.3.RELEASE/reference/html/#feign-logging
  +
 
spring:
 
spring:
profiles: local
 
 
autoconfigure:
 
autoconfigure:
 
exclude[0]: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
 
exclude[0]: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
 
exclude[1]: org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration
 
exclude[1]: org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration
  +
jackson.serialization.INDENT_OUTPUT: true
  +
  +
spring.jpa:
  +
properties.hibernate:
  +
show_sql: true
  +
format_sql: true
  +
use_sql_comments: true
   
 
# https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html#production-ready-endpoints-enabling-endpoints
 
# https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html#production-ready-endpoints-enabling-endpoints
 
management.endpoints:
 
management.endpoints:
 
enabled-by-default: true
 
enabled-by-default: true
shutdown.enabled: true
+
shutdown.enabled: false
 
web.exposure.include: "*"
 
web.exposure.include: "*"
  +
jmx.exposure.include: "*"
  +
jmx.exposure.exclude:
   
 
resttemplate:
 
resttemplate:
 
base:
 
base:
 
url: http://localhost:8080
 
url: http://localhost:8080
  +
  +
spring.data.mongodb:
  +
host: 127.0.0.1
  +
port: 27017
  +
username: ${MONGODB_USER}
  +
password: ${MONGODB_PASSWORD}
  +
authentication-database: ${MONGODB_AUTH_DATABASE}
   
 
</syntaxhighlight>
 
</syntaxhighlight>

Latest revision as of 00:48, 21 March 2023

Overview

Spring Framework

References

General

Notes

  • Annotation injection is performed before XML injection, thus the latter configuration will override the former for properties wired through both approaches.
  • The @Required annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring. The container throws an exception if the affected bean property has not been populated; this allows for eager and explicit failure, avoiding NullPointerExceptions or the like later on. It is still recommended that you put assertions into the bean class itself, for example, into an init method. Doing so enforces those required references and values even when you use the class outside of a container.

Resource

Prefix Example Remarks
classpath: classpath:com/myapp/config.xml
file: file:///data/config.xml
http: https://myserver/logo.png
Class/Interface Description Remarks
Resource Interface for a resource descriptor that abstracts from the actual type of underlying resource, such as a file or class path resource.
ClassPathResource Resource implementation for class path resources.
FileSystemResource Resource implementation for java.io.File and java.nio.file.Path handles with a file system target.
ResourceUtils Utility methods for resolving resource locations to files in the file system.

Container

  EnvironmentCapable <--------------------------------+
                                                      |
  BeanFactory <--+--- ListableBeanFactory ------------+                 LifeCycle <-------------+
                 |                                    |                                         |
                 +--- HierarchicalBeanFactory --------+                                         |
                                                      +--- ApplicationContext <---- ConfigurableApplicationContext
  MessageSource <-------------------------------------+
                                                      |
  ApplicationEventPublisher <-------------------------+
                                                      |
  ResourceLoader <---- ResourcePatternResolver <------+
Interface Description Methods Remarks
ApplicationContext Central interface to provide configuration for an application. read-only while the application is running
EnvironmentCapable indicating a component that contains and exposes an Environment reference. getEnvironment() Environment
ListableBeanFactory Extension of the BeanFactory interface to be implemented by bean factories that can enumerate all their bean instances, rather than attempting bean lookup by name one by one as requested by clients. getBeanDefinitionNames(), getBeanNamesForType(), getBeanNamesForAnnotation()
MessageSource Strategy interface for resolving messages, with support for the parameterization and internationalization of such messages. getMessage() ReloadableResourceBundleMessageSource
ResourcePatternResolver Strategy interface for resolving a location pattern (for example, an Ant-style path pattern) into Resource objects. getResources(String pattern), getResource()
 
  DefaultResourceLoader
         |
         +----- AbstractApplicationContext
         |           |
         |           +----- AbstractRefreshableApplicationContext
         |                       |
         |                       +----- AbstractRefreshableConfigApplicationContext
         |                                   |
         |                                   +----- AbstractRefreshableWebApplicationContext
         |                                   |           |
         |                                   |           +----- AnnotationConfigWebApplicationContext 
         |                                   |           +----- GroovyWebApplicationContext
         |                                   |           +----- XmlWebApplicationContext
         |                                   |
         |                                   +----- AbstractXmlApplicationContext
         |                                   |           |
         |                                   |           +------- ClassPathXmlApplicationContext
         |                                   |           +------- FileSystemXmlApplicationContext
         |                                   |
         |                                   +----- AnnotationConfigReactiveWebApplicationContext
         +----- GenericApplicationContext
                     |
                     +----- AnnotationConfigApplicationContext
                     +----- GenericGroovyApplicationContext
                     +----- GenericReactiveWebApplicationContext
                     |           |
                     |           +----- ReactiveWebServerApplicationContext
                     |                       |
                     |                       +----- AnnotationConfigReactiveWebServerApplicationContext 
                     |
                     +----- GenericWebApplicationContext
                     |           |
                     |           +----- ServletWebServerApplicationContext
                     |                       |
                     |                       +----- AnnotationConfigServletWebServerApplicationContext
                     |                       +----- XmlServletWebServerApplicationContext
                     |
                     +----- GenericXmlApplicationContext
                     +----- ResourceAdapterApplicationContext
                     +----- StaticApplicationContext
                                 |
                                 +----- StaticWebApplicationContext

Configuration

  • Annotation-based Container Configuration
    • @Required, @Autowired, @Inject, @Named
    • Annotation injection is performed before XML injection. Thus, the XML configuration overrides the annotations for properties wired through both approaches.
    • The @Required annotation is formally deprecated as of Spring Framework 5.1, in favor of using constructor injection for required settings.
  • Java-based Container Configuration
    • @Configuration, @Bean, @PropertySource
    • The @Bean annotation is used to indicate that a method instantiates, configures, and initializes a new object to be managed by the Spring IoC container.
    • The @Bean annotation plays the same role as the <bean/> element.
    • Annotating a class with @Configuration indicates that its primary purpose is as a source of bean definitions.

API

Annotation Package Annotations Remarks
@Configuration o.s.context.annotation Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime. @Component
@ComponentScan o.s.context.annotation Configures component scanning directives for use with @Configuration classes. <context:component-scan>
@Import o.s.context.annotation Indicates one or more @Configuration classes to import.
@EnableAsync o.s.scheduling.annotation Enables Spring's asynchronous method execution capability. @Async
@EnableScheduling o.s.scheduling.annotation Enables Spring's scheduled task execution capability. @Scheduled
@SpringBootApplication o.s.boot.autoconfigure Indicates a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning @Configuration, @EnableAutoConfiguration, @ComponentScan
@EnableAutoConfiguration o.s.boot.autoconfigure Enable auto-configuration of the Spring Application Context, attempting to guess and configure beans that you are likely to need. exclude, excludeName

Properties

API

Item Type Description Remarks
PropertyPlaceholderConfigurer class
PropertySourcesPlaceholderConfigurer class
PropertiesLoaderSupport.setLocalOverride(boolean localOverride) method
EmbeddedValueResolverAware class
propertyPlaceholder type XML
property-placeholder element XML

Benas

  <bean id="registeringIdentificationListener" class="org.springframework.beans.factory.config.MethodInvokingBean"
    depends-on="listenableDetectionService, defaultDetectionListener">
    <property name="targetObject" ref="listenableDetectionService"/>
    <property name="targetMethod" value="addListener"/>
    <property name="arguments" ref="defaultDetectionListener"/>
  </bean>
  • Bean Lifecycle Callbacks
    • Initializing : @PostConstruct methods -> InitializingBean.afterPropertiesSet() -> bean@init-method
    • Destroying : @PreDestroy methods -> DisposableBean.destroy() -> bean@destroy-method

API

Class Package Description Remarks
@Bean o.s.context.annotation Indicates that a method produces a bean to be managed by the Spring container. @Configuration
@Component o.s.stereotype Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning. @ComponentScan
@Required o.s.beans.factory.annotation Marks a method (typically a JavaBean setter method) as being 'required': that is, the setter method must be configured to be dependency-injected with a value. Deprecated as of 5.1
@Autowired o.s.beans.factory.annotation Marks a constructor, field, setter method, or config method as to be autowired by Spring's dependency injection facilities. JSR-330 @Inject
@Primary o.s.context.annotation Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency.
@Qualifier o.s.beans.factory.annotation This annotation may be used on a field or parameter as a qualifier for candidate beans when autowiring.
@Resource javax.annotation The Resource annotation marks a resource that is needed by the application. @Autowired
@ManagedBean javax.annotation The ManagedBean annotation marks a POJO as a ManagedBean.A ManagedBean supports a small set of basic services such as resource injection, lifecycle callbacks and interceptors. @Component
@Named javax.inject String-based qualifier.
@Inject javax.inject Identifies injectable constructors, methods, and fields. @Autowired
@Scope
@Lazy
@PostConstruct javax.annotation used on a method that needs to be executed after dependency injection is done to perform any initialization.
@PreDestroy javax.annotation used on a method as a callback notification to signal that the instance is in the process of being removed by the container.
@Conditional o.s.context.annotation Indicates that a component is only eligible for registration when all specified conditions match.
@Profile o.s.context.annotation Indicates that a component is eligible for registration when one or more specified profiles are active.
@ConditionalOnProperty o.s.b.autoconfigure.condition Conditional that checks if the specified properties have a specific value.

Annotations

Purpose Package Annotations
Denoting the roles of types or methods in the overall architecture o.s.stereotype @Component, @Controller, @Repository, @Service
Bean configuration o.s.beans.factory.annotation @Autowired, @Required, @Value, ...
ApplicationContext support o.s.context.annotation @Bean, @ComponentScan, @Conditional, @Configuration, @Lazy, @Profile, @Scope, ...
Asynchronous method execution o.s.scheduling.annotation @Async, @Scheduled
Binding requests to controllers and handler methods o.s.web.bind.annotation @RestController, @GetMapping, @PostMapping, @PutMapping, @PathVariable, @RequestBody, @ResponseBody, ...
Transaction demarcation o.s.transaction.annotation @Transactional, @EnableTransactionManagement
Annotation-driven tests o.s.test.annotation @IfProfileValue, @Repeat, @Rollback, @Timed
MBean exposure o.s.jmx.export.annotation @ManagedResource, @ManagedAttribute, @ManagedOperation
Declaratively configuring field formatting rules o.s.format.annotation @DateTimeFormat, @NumberFormat
Spring Boot's auto-configuration capabilities. o.s.boot.autoconfigure @EnableAutoConfiguration, @SpringBootApplication

SpEL

Transaction

API

Class Description Remarks
@Transactional Describes transaction attributes on a method or class.
@TransactionConfiguration Defines class-level metadata for configuring transactional tests.
@Rollback Indicate whether or not the transaction for the annotated test method should be rolled back after the test method has completed.

AOP

Concurrency

API

Class Description Remarks
TaskExecutor Simple task executor interface that abstracts the execution of a Runnable.
ExecutorServiceAdapter Adapter that takes a Spring TaskExecutor and exposes a full java.util.concurrent.ExecutorService for it.
ConcurrentTaskExecutor Adapter that takes a java.util.concurrent.Executor and exposes a Spring TaskExecutor for it.
ThreadPoolTaskExecutor JavaBean that allows for configuring a ThreadPoolExecutor in bean style (through its "corePoolSize", "maxPoolSize", "keepAliveSeconds", "queueCapacity" properties) and exposing it as a Spring TaskExecutor.
ThreadPoolExecutorFactoryBean JavaBean that allows for configuring a ThreadPoolExecutor in bean style (through its "corePoolSize", "maxPoolSize", "keepAliveSeconds", "queueCapacity" properties) and exposing it as a bean reference of its native ExecutorService type.
@Scheduled
@Async

Internationalization

API

Class Description Remarks
o.s.context.MessageSource
o.s.context.support.ResourceBundleMessageSource
o.s.context.support.ReloadableResourceBundleMessageSource

Source

Web MVC

API

Class Package Description Remarks
HttpHeaders javax.ws.rs.core An injectable interface that provides access to HTTP header information.
HttpHeaders o.s.http A data structure representing HTTP request or response headers.
HttpHeaders org.apache.http Constants enumerating the HTTP headers. RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), RFC2518 (WebDAV)
MediaType javax.ws.rs.core An abstraction for a media type.
MediaType o.s.http
ContentType org.apache.http.entity Content type information consisting of a MIME type and an optional charset.
HttpEntity<T> o.s.http
RequestEntity<T> o.s.http
ResponseEntity<T> o.s.http
@RequestMapping o.s.web.bind.annotation Annotation for mapping web requests onto methods in request-handling classes with flexible method signatures.
@GetMapping o.s.web.bind.annotation Annotation for mapping HTTP GET requests onto specific handler methods.
@PostMapping o.s.web.bind.annotation Annotation for mapping HTTP POST requests onto specific handler methods.
@PathVariable o.s.web.bind.annotation Annotation which indicates that a method parameter should be bound to a URI template variable.
@RequestParam o.s.web.bind.annotation Annotation which indicates that a method parameter should be bound to a web request parameter. since v2.5. In Spring MVC, "request parameters" map to query parameters, form data, and parts in multipart requests.
@RequestHeader o.s.web.bind.annotation Annotation which indicates that a method parameter should be bound to a web request header.
@SessionAttribute o.s.web.bind.annotation Annotation to bind a method parameter to a session attribute.
@RequestBody o.s.web.bind.annotation Annotation indicating a method parameter should be bound to the body of the web request. since v3.0
@RequestPart o.s.web.bind.annotation Annotation that can be used to associate the part of a "multipart/form-data" request with a method argument. since v3.1
CommonsRequestLoggingFilter o.s.web.filter Simple request logging filter that writes the request URI (and optionally the query string) to the Commons Log.

REST

Class Description Remark
RestTemplate (source) Synchronous client to perform HTTP requests, exposing a simple, template method API over underlying HTTP client libraries such as the JDK HttpURLConnection, Apache HttpComponents, and others.
HttpComponentsClientHttpRequestFactory ClientHttpRequestFactory implementation that uses Apache HttpComponents HttpClient to create requests.
SimpleClientHttpRequestFactory ClientHttpRequestFactory implementation that uses standard JDK facilities.
Netty4ClientHttpRequestFactory ClientHttpRequestFactory implementation that uses Netty 4 to create requests.
HttpMessageConverter<T>
Jaxb2RootElementHttpMessageConverter Implementation of HttpMessageConverter that can read and write XML using JAXB2.
MappingJackson2HttpMessageConverter (source) Implementation of HttpMessageConverter that can read and write JSON using Jackson 2.x's ObjectMapper.
MappingJackson2XmlHttpMessageConverter Implementation of HttpMessageConverter that can read and write XML using Jackson 2.x extension component for reading and writing XML encoded data.
MappingJackson2SmileHttpMessageConverter Implementation of HttpMessageConverter that can read and write Smile data format ("binary JSON") using the dedicated Jackson 2.x extension.
Jackson2ObjectMapperBuilder A builder used to create ObjectMapper instances with a fluent API.

Exception Handling

Filters

Class Package Description Remarks
CommonsRequestLoggingFilter o.s.web.filter Simple request logging filter that writes the request URI (and optionally the query string) to the Commons Log.

misc

JMX

  • ManagedResource Annotation is not annoted as Inherited
    • We finally changed @ManagedResource to inherited now. Potential object name collisions need to be dealt with; the general recommendation is to not specify an object name value in @ManagedResource at all when using it on a base class.

API

Annotation Package Annotations Remarks
@ManagedResource o.s.jmx.export.annotation Class-level annotation that indicates to register instances of a class with a JMX server, corresponding to the ManagedResource attribute.
@ManagedAttribute o.s.jmx.export.annotation Method-level annotation that indicates to expose a given bean property as a JMX attribute, corresponding to the ManagedAttribute attribute.
@ManagedOperation o.s.jmx.export.annotation Method-level annotation that indicates to expose a given method as a JMX operation, corresponding to the ManagedOperation attribute.

Jackson

eMail

Class/Interface Description Remarks
JavaMailSender Extended MailSender interface for JavaMail, supporting MIME messages both as direct arguments and through preparation callbacks.
JavaMailSenderImpl (source) Production implementation of the JavaMailSender interface, supporting both JavaMail MimeMessages and Spring SimpleMailMessages. protected void doSend()
SimpleMailMessage Models a simple mail message, including data such as the from, to, cc, subject, and text fields.
MimeMessageHelper Helper class for populating a MimeMessage.
Class/Interface Description Remarks
javax.mail.Session The Session class represents a mail session and is not subclassed. A single default session can be shared by multiple applications on the desktop. Unshared sessions can also be created.
javax.mail.Transport An abstract class that models a message transport.
Field Description Remarks
From The email address, and optionally the name of the author(s)
To The email address(es), and optionally name(s) of the message's recipient(s) Recipients
Cc Carbon copy recipients
Bcc Blind carbon copy recipients
Date The local time and date when the message was written.
Subject A brief summary of the topic of the message.
Content-Type Information about how the message is to be displayed, usually a MIME type
Message-ID
In-Reply-To Message-ID of the message that this is a reply to.
References Message-ID of the message that this is a reply to, and the message-id of the message the previous reply was a reply to, etc.
Reply-To Address that should be used to reply to the message.
Sender Address of the actual sender acting on behalf of the author listed in the From: field

misc

Spring Boot

References

Spring Boot 2.2

Spring Boot 2.1

Spring Boot 2.0

Spring Boot 1.5

General

Configuration

  • The @Value Annotation in Spring
    • basic form: @Value("${car.brand")
    • default valued form: @Value("${car.type:Sedan}")
    • SpEL form: @Value("#{systemProperties['user.name']}")

API

Class/Interface Description Remarks
WebMvcAutoConfiguration (source) Auto-configuration for Web MVC. localeResolver()
MessageSourceAutoConfiguration (source) Auto-configuration for MessageSource.
Environment Interface representing the environment in which the current application is running.

Actuator

Endpoint Description Remarks
beans Displays a complete list of all the Spring beans in your application.
env Exposes properties from Spring’s ConfigurableEnvironment.

Error Control

Class Package Description Remarks
BasicErrorController (source) o.s.b.autoconfigure.web
AbstractErrorController (source) o.s.b.autoconfigure.web
DefaultErrorAttributes (source) o.s.b.autoconfigure.web

Logging

  • How to log SQL statements in Spring Boot?
    • logging.level.org.hibernate.SQL=DEBUG
    • logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
    • logging.level.org.hibernate.type=TRACE
    • spring.jpa.properties.hibernate.show_sql=true
    • spring.jpa.properties.hibernate.format_sql=true
    • spring.jpa.properties.hibernate.use_sql_comments=true

REST

Database

Property Type/Values Description Remarks
spring.datasource.initialization-mode always, never
spring.datasource.continue-on-error
spring.sql.init.mode always, never
spring.sql.init.continue-on-error
spring.jpa.generate-ddl boolean switches the feature on and off and is vendor independent
spring.jpa.hibernate.ddl-auto none, validate, update, create, create-drop a Hibernate feature that controls the behavior in a more fine-grained way
spring.jpa.defer-datasource-initialization boolean
Property Type/Values Default Description Remarks
spring.datasource.hikari.connection-timeout integer 2,000 maximum number of milliseconds that a client will wait for a connection
spring.datasource.hikari.minimum-idle integer 10 minimum number of idle connections maintained by HikariCP in a connection pool
spring.datasource.hikari.maximum-pool-size integer 10 maximum pool size
spring.datasource.hikari.idle-timeout integer maximum idle time for connection
spring.datasource.hikari.max-lifetime integer maximum lifetime in milliseconds of a connection in the pool after it is closed.
spring.datasource.hikari.auto-commit boolean true default auto-commit behavior

Test

Spring Test

Class/Package Description Remarks
@ContextConfiguration Defines class-level metadata that is used to determine how to load and configure an ApplicationContext for integration tests.
MockMvc Main entry point for server-side Spring MVC test support.
SpringExtension integrates the Spring TestContext Framework into JUnit 5's Jupiter programming model.
@SpringJUnitConfig A composed annotation that combines @ExtendWith(SpringExtension.class) from JUnit Jupiter with @ContextConfiguration from the Spring TestContext Framework.

Spring Boot Test

Class/Package Description Remarks
@SpringBootTest Annotation that can be specified on a test class that runs Spring Boot based tests.
enum SpringBootTest.WebEnvironment An enumeration web environment modes DEFINED_PORT, MOCK, NONE, RANDOM_PORT
@TestConfiguration @Configuration that can be used to define additional beans or customizations for a test. @TestConfiguration
@MockBean Annotation that can be used to add mocks to a Spring ApplicationContext.
@WebMvcTest Using this annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests (@Controller but not @Component, @Service or @Repository @AutoConfigureWebMvc, @AutoConfigureMockMvc
@AutoConfigureMockMvc Annotation that can be applied to a test class to enable and configure auto-configuration of MockMvc.
@DataJpaTest Annotation for a JPA test that focuses only on JPA components. @AutoConfigureTestDatabase
@AutoConfigureTestDatabase Annotation that can be applied to a test class to configure a test database to use instead of any application defined or auto-configured data source. AutoConfigureTestDatabase.Replace
  • Auto configuration not necessary for unit testing
@EnableAutoConfiguration(exclude = {
    EndpointAutoConfiguration.class,    //o.s.b.actuate.autoconfigure.endpoint.EndpointAutoConfiguration
    JmxEndpointAutoConfiguration.class,
    InfoContributorAutoConfiguration.class,
    CompositeMeterRegistryAutoConfiguration.class,
    JvmMetricsAutoConfiguration.class,
    LogbackMetricsAutoConfiguration.class,
    MetricsAutoConfiguration.class,
    SystemMetricsAutoConfiguration.class,
    SimpleMetricsExportAutoConfiguration.class,
    HttpClientMetricsAutoConfiguration.class,
    MappingsEndpointAutoConfiguration.class,
    ManagementContextAutoConfiguration.class,
    ConditionsReportEndpointAutoConfiguration.class,
    DataSourceAutoConfiguration.class,
    DataSourceTransactionManagerAutoConfiguration.class,
    HibernateJpaAutoConfiguration.class,
    SecurityAutoConfiguration.class,
    OAuth2ClientAutoConfiguration.class,
    ReactiveOAuth2ClientAutoConfiguration.class,
    OAuth2ResourceServerAutoConfiguration.class,
    ReactiveOAuth2ResourceServerAutoConfiguration.class,
    FeignAutoConfiguration.class,
    TraceWebClientAutoConfiguration.class
})

Test Class Templates

Test class explicitly optimized

When testing service or repository classes, to execute the test more quickly, it is desirable not to load unnecessary beans such as MVC beans or actuator configuration beans. The following code sample shows how to do it.

@SpringBootTest(
    properties = { "management.endpoints.enabled-by-default=false" },
    webEnvironment=WebEnvironment.MOCK                   // NONE, MOCK, ...
)
@EnableAutoConfiguration(exclude = {
    EndpointAutoConfiguration.class,                      //o.s.b.actuate.autoconfigure.endpoint.EndpointAutoConfiguration
    WebEndpointAutoConfiguration.class,
    JmxEndpointAutoConfiguration.class,                   //o.s.b.actuate.autoconfigure.endpoint.jmx.JmxEndpointAutoConfiguration
    MappingsEndpointAutoConfiguration.class,              //o.s.b.actuate.autoconfigure.web.mappings.MappingsEndpointAutoConfiguration
    CompositeMeterRegistryAutoConfiguration.class,        //o.s.b.actuate.autoconfigure.metrics.CompositeMeterRegistryAutoConfiguration
    MetricsAutoConfiguration.class,                       //o.s.b.actuate.autoconfigure.metrics.MetricsAutoConfiguration
    JvmMetricsAutoConfiguration.class,                    //o.s.b.actuate.autoconfigure.metrics.JvmMetricsAutoConfiguration
    SystemMetricsAutoConfiguration.class,                 //o.s.b.actuate.autoconfigure.metrics.SystemMetricsAutoConfiguration
    LogbackMetricsAutoConfiguration.class,                //o.s.b.actuate.autoconfigure.metrics.LogbackMetricsAutoConfiguration
    HttpClientMetricsAutoConfiguration.class,             //o.s.b.actuate.autoconfigure.metrics.web.client.HttpClientMetricsAutoConfiguration
    SimpleMetricsExportAutoConfiguration.class,           //o.s.b.actuate.autoconfigure.metrics.export.simple.SimpleMetricsExportAutoConfiguration
    ManagementContextAutoConfiguration.class,             //o.s.b.actuate.autoconfigure.web.server.ManagementContextAutoConfiguration
    ServletManagementContextAutoConfiguration.class,
    ConditionsReportEndpointAutoConfiguration.class,      //o.s.b.actuate.autoconfigure.condition.ConditionsReportEndpointAutoConfiguration
    InfoContributorAutoConfiguration.class,               //o.s.b.actuate.autoconfigure.info.InfoContributorAutoConfiguration
    HealthContributorAutoConfiguration.class,
    DiskSpaceHealthContributorAutoConfiguration.class,
    DataSourceAutoConfiguration.class,                    //o.s.b.autoconfigure.jdbc.DataSourceAutoConfiguration
    DataSourceTransactionManagerAutoConfiguration.class,  //o.s.b.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
    HibernateJpaAutoConfiguration.class,                  //o.s.b.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
    SecurityAutoConfiguration.class,                      //o.s.b.autoconfigure.security.servlet.SecurityAutoConfiguration
    OAuth2ClientAutoConfiguration.class,                  //o.s.b.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration
    ReactiveOAuth2ClientAutoConfiguration.class,          //o.s.b.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration
    OAuth2ResourceServerAutoConfiguration.class,          //o.s.b.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration
    ReactiveOAuth2ResourceServerAutoConfiguration.class,  //o.s.b.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration
    FeignAutoConfiguration.class,                         //o.s.cloud.openfeign.FeignAutoConfiguration
    TraceWebClientAutoConfiguration.class                 //o.s.cloud.sleuth.instrument.web.client.TraceWebClientAutoConfiguration
})
@TestInstance(Lifecycle.PER_CLASS)
public class ApplicationInOptimalTest{

  private Logger logger = LoggerFactory.getLogger(this.getClass());

  // Define additional beans or customizations for a test.
  // Automatically loaded by @SpringBootTest without 'classes' property
  @TestConfiguration
  static class ExtraConfig{
      
    @Bean
    public CatalogService testCatalogService(){
       ...
    }
  }

  @Autowired
  private ApplicationContext springContext;

  @Autowired
  private OrderService orderService;

  @Autowired
  private CatalogService catalogService;

  @Test
  public void testGetBeanDefinitionNames() {

    final int cnt = springContext.getBeanDefinitionCount();
    final String[] names = springContext.getBeanDefinitionNames();
    Arrays.sort(names);

    this.logger.info("Defined Beans : {}", cnt);
    for(String name: names) this.logger.info("  - {}", name);

    Assertions.assertTrue(cnt > 0, "The Spring container has no bean which makes no sense.");
    Assertions.assertTrue(Arrays.binarySearch(names, "web3j") > -1, "The Spring container doesn't contain 'web3j' bean, which is never expected.");
    Assertions.assertTrue(Arrays.binarySearch(names, "mvcViewResolver") < 0, "The Spring container still contains 'mvcViewResolver' bean, which is not expected.");
  }

  @Test
  public void testGetConfigurations() {

    final Map<String, Object> configs = springContext.getBeansWithAnnotation(Configuration.class);
    final int cnt = configs.size();

    this.logger.info("Configurations : {}", cnt);
    configs.forEach((k, v) -> this.logger.info("   - {} : {}", k, v));

    Assertions.assertTrue(cnt > 0, "The Spring container has no configuration, which is impossible.");
  }
}
Test class for literally unit test

It is possible to auto-wire test-purpose bean instead of a bean in normal(non-test) Spring Boot configuration (like EthereumClientConfig in below example) by defining @Primary bean in the extra configuration imported only by test.

@SpringBootTest(
    classes = {IdentityManagerContractServiceImpl.class, EthereumClientConfig.class},
    properties = {"management.endpoints.enabled-by-default=false", "security=", "spring.security.enabled=false"},
    webEnvironment = WebEnvironment.NONE)
@TestInstance(Lifecycle.PER_CLASS)
@Import(IdentityManagerContractServiceImplTest.ExtraConfig.class)
class IdentityManagerContractServiceImplTest{

  final private Logger logger = LoggerFactory.getLogger(this.getClass());

  // Define additional beans or customizations for a test.
  // NOT loaded automatically by @SpringBootTest with 'classes' property
  // Use '@Import' to load explicitly
  @TestConfiguration
  static class ExtraConfig{
     ...

     // Make another bean instead of a bean in normal configuration to be autowired using @Primary annotation.
     @Bean @Primary
     SendTxProcessor sendTxProcessorWithoutRetry(){
        ...
     }
  }

  @SpyBean
  private TestSpecialAccountServiceImpl specialAccountSrv;

  @Autowired
  private IdentityManagerContractService identityManagerContract;

  ...

}
Test class for concurrency behavior

To test a method in concurrent executions, apply parallel execution(@Execution(CONCURRENT)) and repeated test(@RepeatedTest) together. The life-cycle of the test instance is expected to be PER_METHOD.

@SpringBootTest(
    classes = {SafeTokenContractServiceImpl.class, EthereumClientConfig.class},
    properties = {"management.endpoints.enabled-by-default=false", "security=", "spring.security.enabled=false"},
    webEnvironment = WebEnvironment.NONE)
@Import(SafeTokenContractServiceImplConcurrentTest.ExtraConfig.class)
@TestInstance(Lifecycle.PER_METHOD)
@Execution(ExecutionMode.CONCURRENT)
public class SafeTokenContractServiceImplConcurrentTest{

  final private Logger logger  = LoggerFactory.getLogger(this.getClass());

  @TestConfiguration
  static class ExtraConfig{

    @Bean
    public AccountService testAccountService() throws Exception {
      ...
    }

    ...
  }

  @Value("${smart-contracts.safe-token.address}")
  private String tokenAddress;

  @Autowired
  private AccountService accountSrv;

  @Autowired
  private SafeTokenContractServiceImpl tokenContractSrv;

  @RepeatedTest(10)
  @Execution(ExecutionMode.CONCURRENT)
  public void testMint() {
    ...
    try {
      this.tokenContractSrv.mint(from, to, amt);
    }catch(Exception ex) {
      this.logger.error("Fail to execute `mint`", ex);
      throw ex;
    }
  }

For the above test case to run correctly not affecting other test cases that has no @EXECUTION(CONCURRENT), following is proper for JUnit Platform configuration file(junit-platform.properties).

! https://junit.org/junit5/docs/current/user-guide/#running-tests-config-params
! https://junit.org/junit5/docs/current/user-guide/#writing-tests-parallel-execution

junit.jupiter.testinstance.lifecycle.default = per_class
junit.jupiter.execution.parallel.enabled = true
# junit.jupiter.execution.parallel.mode.default = concurrent
# junit.jupiter.execution.parallel.mode.classes.default = concurrent
Test class for only JPA repositories
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@TestInstance(Lifecycle.PER_CLASS)
class SpecialAccountRepositoryTest{

  final private Logger logger = LoggerFactory.getLogger(this.getClass());

  @Autowired
  private SpecialAccountRepository specialAccountRepos;

  ...

}

misc

Spring Security

References

Spring Security 5.1

Spring Security 4.2.2

Spring Security 3.1

Concepts

Concept Description API Remarks
Principal the abstract notion of a principal, which can be used to represent any entity, such as an individual, a corporation, and a login id java.security.Principal Party
Subject a grouping of related information for a single entity, such as a person, including the Subject's identities as well as its security-related attributes (passwords and cryptographic keys, for example) javax.security.auth.Subject A subject can contain multiple principals and a principal represents the face of a subject.
Authentication authenticated principal o.s.security.core.Authentication interface Authentication extends Principal
GrantedAuthority application-wide permissions granted to a principal o.s.security.core.GrantedAuthority Role

API

Class Source Description Remarks
Authentication
UsernamePasswordAuthenticationToken An Authentication implementation that is designed for simple presentation of a username and password
TestingAuthenticationToken An Authentication implementation that is designed for use whilst unit testing

General

Session Management

Authentication

Authorization

Spring Session

References

Spring Session 1.3.0

Spring Integration

Spring Data

  • Projects
Project Description Documentation API Remarks
Spring Data Commons part of the umbrella Spring Data project that provides shared infrastructure across the Spring Data projects and contains technology neutral repository interfaces as well as a metadata model for persisting Java classes. Spring Data Commons Reference
  • Common Annotations
Annotation Description Remarks
@Id Demarcates an identifier.
@AccessType Define how Spring Data shall access values of persistent properties. Type.FIELD | TYPE.PROPERTY

Spring Data JPA

  • JPA Annotations
  • javax.persistence package
    • @Entity, @Table, @Column, @Id, @IdClass, @Transient, @Temporal, @ForeignKey, @Index, @UniqueConstraint, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany, @JoinColumn, @JoinTable, @Inheritance, @DiscriminatorColumn, @DiscriminatorValue
Annotation Description Remarks
@Entity Specifies that the class is an entity
@Table Specifies the primary table for the annotated entity name, catalog
@Column Specifies the mapped column for a persistent property or field name, columnDefinition, nullable, unique, length, precision, scale
@Id Specifies the primary key of an entity
@IdClass Specifies a composite primary key class that is mapped to multiple fields or properties of the entity
@Transient Specifies that the property or field is not persistent
@Temporal Specified for persistent fields or properties of type java.util.Date and java.util.Calendar
@ForeignKey Used to specify the handling of foreign key constraints when schema generation is in effect
@Index Used in schema generation to specify creation of an index
@UniqueConstraint Specifies that a unique constraint is to be included in the generated DDL for a primary or secondary table

Spring Data MongoDB

Core Classes

Class Description Source Remarks
AbstractMongoClientConfiguration Base class for Spring Data MongoDB configuration using JavaConfig with MongoClient. AbstractMongoClientConfiguration.java@3.1.3
MongoJsonSchemaCreator Extracts the MongoJsonSchema for a given Class by applying the following mapping rules. factory method
Annotation Description Source Remarks
@Document Identifies a domain object to be persisted to MongoDB.
@Field Annotation to define custom metadata for document fields.
@Indexed Mark a field to be indexed using MongoDB's indexing feature.

Readings

  • Spring Data MongoDB Property Population
    1. If the property is immutable but exposes a with… method, we use the with… method to create a new entity instance with the new property value.
    2. If property access (i.e. access through getters and setters) is defined, we’re invoking the setter method.
    3. If the property is mutable we set the field directly.
    4. If the property is immutable we’re using the constructor to be used by persistence operation to create a copy of the instance.
    • By default, we set the field value directly.

Typical Code Samples

Typical configuration bean
/**
 * @author 3rdstage
 *
 * @see <tt><a href='https://github.com/spring-projects/spring-data-mongodb/blob/3.1.3/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/AbstractMongoClientConfiguration.java'>AbstractMongoClientConfiguration.java</a></tt>
 */
@Configuration
@EnableMongoRepositories
public class MongoClientConfig extends AbstractMongoClientConfiguration{

  final private Logger logger = LoggerFactory.getLogger(this.getClass());

  @Bean
  @Override
  public MongoClient mongoClient() {
    return super.mongoClient();
  }

  @Override
  protected String getDatabaseName() {
    return "eth";
  }

  @Override
  protected String getMappingBasePackage() {
    return "thirdstage.eth.disassembly.repos";
  }

  @Override
  public boolean autoIndexCreation() {
    return true;
  }

  // https://docs.spring.io/spring-data/mongodb/docs/3.2.x/reference/html/#mongo.custom-converters.xml
  @Override
  protected void configureConverters(MongoConverterConfigurationAdapter adapter) {
    super.configureConverters(adapter);
    //adapter.registerConverter(new EpochTimeToDateConverter());
    //adapter.registerConverter(new EpochTimeFromDateConverter());
  }

  @Bean
  public MongoClientSettingsBuilderCustomizer customizer() {
    return (builder) -> {
      List<Convention> cvns = Conventions.DEFAULT_CONVENTIONS;
      //cvns.add(Conventions.SET_PRIVATE_FIELDS_CONVENTION);
      CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(
        MongoClientSettings.getDefaultCodecRegistry(),
        CodecRegistries.fromProviders(
            PojoCodecProvider.builder()
              .automatic(true)
              .conventions(cvns)
              .build()));
      builder.codecRegistry(pojoCodecRegistry);
    };
  }
}
Domain Object with custom type conversion using converted typed getter/setter without global type converter
@Getter
@Setter
@RequiredArgsConstructor
@Accessors(chain = true)
@Document(collection = "transactions")
public class Transaction implements java.io.Serializable{

  @Id
  private final String hash;

  @Field(name = "block_no")
  private long blockNo;

  private long index;

  private String from;

  // denormalized field from account
  @Field("from_is_contr")
  private boolean fromIsContract;

  private String to;

  // denormalized field from account
  @Field("to_is_contr")
  private boolean toIsContract;

  @Getter(AccessLevel.NONE)
  @Setter(AccessLevel.NONE)
  @AccessType(AccessType.Type.FIELD)
  @Field(targetType = DECIMAL128)
  private BigDecimal value;

  public BigInteger getValue() {
    return this.value.toBigInteger();
  }

  public Transaction setValue(BigInteger val) {
    this.value = new BigDecimal(val);
    return this;
  }

  @Indexed
  private Instant at;

}

Spring Data Redis

Spring Cloud

Spring Cloud OpenFeign

Version Documentation API Remarks
3.1 Spring Cloud OpenFeign 3.1.0 Reference Spring Cloud OpenFeign Core 3.1.0 API

misc

XML Schemas

Name Namespace Description Sources
beans http://www.springframework.org/schema/beans Defines the elements to define beans. spring-beans-4.0.xsd
context http://www.springframework.org/schema/context Defines the configuration elements for the Spring Framework's application. org.springframework.context.config

spring-context-4.0.xsd

aop http://www.springframework.org/schema/aop Defines the configuration elements for the Spring Framework's AOP support. org.springframework.aop.config

spring-aop-4.0.xsd

jdbc http://www.springframework.org/schema/jdbc Defines the configuration elements for the Spring Framework's embedded database support. org.springframework.jdbc.config

spring-jdbc-4.0.xsd

tx http://www.springframework.org/schema/tx Defines the elements used in the Spring Framework's declarative transaction management infrastructure. spring-tx-3.0.xsd
mvc http://www.springframework.org/schema/mvc spring-mvc-3.0.xsd
util http://www.springframework.org/schema/util spring-util-4.0.xsd
task http://www.springframework.org/schema/task/ spring-task-4.2.xsd

Projects

Spring Retry

Samples

Common Spring Boot Application Configuration

# https://docs.spring.io/spring-boot/docs/2.2.x/reference/html/appendix-application-properties.html

debug: !!bool ${SPRING_DEBUG:false}
trace: !!bool ${SPRING_TRACE:false}

logging.level:
  org.springframework: INFO
  org.springframework.boot.autoconfigure: WARN
  org.apache.tomcat: INFO
  org.apache.catalina: INFO
  org.eclipse.jetty: INFO
  org.hibernate.SQL: WARN
  org.hibernate.type: WARN
  org.hibernate.tool.hbm2ddl: TRACE

server:
  port: 8080

jwt:
  secret: javainuse

spring:
  application.name: foo-bar
  profiles:
    active: local
  main.allow-bean-definition-overriding: false
  output:
    ansi:
      enabled: always  # https://docs.spring.io/spring-boot/docs/2.1.x/reference/html/boot-features-logging.html#boot-features-logging-color-coded-output
  servlet:
    multipart:
      max-file-size: 100MB
      max-request-size: 100MB

spring.aop:
  auto: true  # Add @EnableAspectJAutoProxy.
  proxy-target-class: true  # Whether subclass-based (CGLIB) proxies are to be created (true), as opposed to standard Java interface-based proxies (false).

spring.security:
  user:
    name: boot
    password: boot

springdoc:
  use-fqn: false
  swagger-ui:
    show-common-extensions: true
    default-model-rendering: "example"   # ("example" | "model")
    default-models-expand-depth: 5
    default-model-expand-depth: 5
    disable-swagger-default-url: false
    #validator-url: 'none'   # 'none' : no validation
  api-docs:
    path: /swagger-ui/api-docs
    enabled: true

---
spring.profiles: local

debug: !!bool ${SPRING_DEBUG:true}
trace: !!bool ${SPRING_TRACE:false}

logging.level:
  org.hibernate.SQL: DEBUG
  org.hibernate.type: TRACE
  # https://cloud.spring.io/spring-cloud-static/spring-cloud-openfeign/2.2.3.RELEASE/reference/html/#feign-logging

spring:
  autoconfigure:
    exclude[0]: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
    exclude[1]: org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration
  jackson.serialization.INDENT_OUTPUT: true

spring.jpa:
  properties.hibernate:
    show_sql: true
    format_sql: true
    use_sql_comments: true

# https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html#production-ready-endpoints-enabling-endpoints
management.endpoints:
  enabled-by-default: true
  shutdown.enabled: false
  web.exposure.include: "*"
  jmx.exposure.include: "*"
  jmx.exposure.exclude: 

resttemplate:
  base:
    url: http://localhost:8080

spring.data.mongodb:
  host: 127.0.0.1
  port: 27017
  username: ${MONGODB_USER}
  password: ${MONGODB_PASSWORD}
  authentication-database: ${MONGODB_AUTH_DATABASE}

Working of @Transactional annotation according to the processing mode(proxy or aspectj)

Test code outline
  • Annotated method is private : private SearchRequest createAndPersistNewSearchReq()
  • In-call is invoked from testProcess to createAndPersistNewSearchReq()
public class SearchTaskProcessorTest{

  //...
  ConfigurableApplicationContext spring;
  private SearchMasterMapper masterMapper;
  private SearchDetailMapper detailMapper;
  private SearchRoiMapper roiMapper;
  private SearchRoiParamMapper roiParamMapper;
  private SearchRoiPointMapper roiPointMapper;

  @BeforeClass
  public void beforeClass() throws Exception{

    //...
    this.spring = new ClassPathXmlApplicationContext(CONFIG_LOCATION);
    this.spring.registerShutdownHook();
    this.masterMapper = this.spring.getBean("searchMasterMapper", SearchMasterMapper.class);
    this.detailMapper = this.spring.getBean("searchDetailMapper", SearchDetailMapper.class);
    this.roiMapper = this.spring.getBean("searchRoiMapper", SearchRoiMapper.class);
    this.roiParamMapper = this.spring.getBean("searchRoiParamMapper", SearchRoiParamMapper.class);
    this.roiPointMapper = this.spring.getBean("searchRoiPointMapper", SearchRoiPointMapper.class);
  }

  @AfterClass
  public void afterClass(){ }

  @Transactional
  private SearchRequest createAndPersistNewSearchReq(){

    //...
    this.masterMapper.insertSearchMaster(req);
    this.detailMapper.insertSearchDetail(req.getId(), cctv);
    this.roiMapper.insertSearchRoi(req.getId(), cctv.getSystemId(), cctv.getId(), roi);

    for(Param param: roi.getParams()){
      this.roiParamMapper.insertSearchRoiParam(req.getId(), cctv.getSystemId(),
        cctv.getId(), roi.getNo(), param);
    }
    for(Point pt: roi.getPoints()){
      this.roiPointMapper.insertSearchRoiPoint(req.getId(), cctv.getSystemId(),
        cctv.getId(), roi.getNo(), pt);
    }

    return req;
  }

  @Test
  public void testProcess(){

    SearchRequest req = this.createAndPersistNewSearchReq();
    SearchTaskProcessor processor = this.spring.getBean(...);

    //...

    processor.process(req.getId(), "1", crtr);
  }
}


In proxy mode
  • Log