Spring Framework




  • 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.


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 and java.nio.file.Path handles with a file system target.
ResourceUtils Utility methods for resolving resource locations to files in the file system.


  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()
         +----- 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


  • 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.


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



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


  <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 Lifecycle Callbacks
    • Initializing : @PostConstruct methods -> InitializingBean.afterPropertiesSet() -> bean@init-method
    • Destroying : @PreDestroy methods -> DisposableBean.destroy() -> bean@destroy-method


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
@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.


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




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.




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.



Class Description Remarks




Class Package Description Remarks
HttpHeaders 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 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.
@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.
CommonsRequestLoggingFilter o.s.web.filter Simple request logging filter that writes the request URI (and optionally the query string) to the Commons Log.


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.
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


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.



  • 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.


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.



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
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


Spring Boot


Spring Boot 2.2

Spring Boot 2.1

Spring Boot 2.0

Spring Boot 1.5



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


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.


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


  • How to log SQL statements in Spring Boot?



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

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.

    properties = { "management.endpoints.enabled-by-default=false" },
    webEnvironment=WebEnvironment.MOCK                   // NONE, MOCK, ...
@EnableAutoConfiguration(exclude = {
    EndpointAutoConfiguration.class,                      //o.s.b.actuate.autoconfigure.endpoint.EndpointAutoConfiguration
    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
    ConditionsReportEndpointAutoConfiguration.class,      //o.s.b.actuate.autoconfigure.condition.ConditionsReportEndpointAutoConfiguration
    InfoContributorAutoConfiguration.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,                      //
    OAuth2ClientAutoConfiguration.class,                  //
    ReactiveOAuth2ClientAutoConfiguration.class,          //
    OAuth2ResourceServerAutoConfiguration.class,          //
    ReactiveOAuth2ResourceServerAutoConfiguration.class,  //
    FeignAutoConfiguration.class,                         //
    TraceWebClientAutoConfiguration.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
  static class ExtraConfig{
    public CatalogService testCatalogService(){

  private ApplicationContext springContext;

  private OrderService orderService;

  private CatalogService catalogService;

  public void testGetBeanDefinitionNames() {

    final int cnt = springContext.getBeanDefinitionCount();
    final String[] names = springContext.getBeanDefinitionNames();
    Arrays.sort(names);"Defined Beans : {}", cnt);
    for(String name: names)"  - {}", 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.");

  public void testGetConfigurations() {

    final Map<String, Object> configs = springContext.getBeansWithAnnotation(Configuration.class);
    final int cnt = configs.size();"Configurations : {}", cnt);
    configs.forEach((k, v) ->"   - {} : {}", 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.

    classes = {IdentityManagerContractServiceImpl.class, EthereumClientConfig.class},
    properties = {"management.endpoints.enabled-by-default=false", "security=", ""},
    webEnvironment = WebEnvironment.NONE)
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
  static class ExtraConfig{

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

  private TestSpecialAccountServiceImpl specialAccountSrv;

  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.

    classes = {SafeTokenContractServiceImpl.class, EthereumClientConfig.class},
    properties = {"management.endpoints.enabled-by-default=false", "security=", ""},
    webEnvironment = WebEnvironment.NONE)
public class SafeTokenContractServiceImplConcurrentTest{

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

  static class ExtraConfig{

    public AccountService testAccountService() throws Exception {


  private String tokenAddress;

  private AccountService accountSrv;

  private SafeTokenContractServiceImpl tokenContractSrv;

  public void testMint() {
    try {, 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.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
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class SpecialAccountRepositoryTest{

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

  private SpecialAccountRepository specialAccountRepos;




Spring Security


Spring Security 5.1

Spring Security 4.2.2

Spring Security 3.1


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 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) A subject can contain multiple principals and a principal represents the face of a subject.
Authentication authenticated principal interface Authentication extends Principal
GrantedAuthority application-wide permissions granted to a principal Role


Class Source Description Remarks
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


Session Management



Spring Session


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

Spring Data MongoDB

Core Classes

Class Description Source Remarks
AbstractMongoClientConfiguration Base class for Spring Data MongoDB configuration using JavaConfig with MongoClient.
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.


  • 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=''></a></tt>
public class MongoClientConfig extends AbstractMongoClientConfiguration{

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

  public MongoClient mongoClient() {
    return super.mongoClient();

  protected String getDatabaseName() {
    return "eth";

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

  public boolean autoIndexCreation() {
    return true;

  protected void configureConverters(MongoConverterConfigurationAdapter adapter) {
    //adapter.registerConverter(new EpochTimeToDateConverter());
    //adapter.registerConverter(new EpochTimeFromDateConverter());

  public MongoClientSettingsBuilderCustomizer customizer() {
    return (builder) -> {
      List<Convention> cvns = Conventions.DEFAULT_CONVENTIONS;
      CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(
Domain Object with custom type conversion using converted typed getter/setter without global type converter
@Accessors(chain = true)
@Document(collection = "transactions")
public class Transaction implements{

  private final String hash;

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

  private long index;

  private String from;

  // denormalized field from account
  private boolean fromIsContract;

  private String to;

  // denormalized field from account
  private boolean toIsContract;

  @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;

  private Instant at;


Spring Data Redis

Spring Cloud


XML Schemas

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


aop Defines the configuration elements for the Spring Framework's AOP support. org.springframework.aop.config


jdbc Defines the configuration elements for the Spring Framework's embedded database support. org.springframework.jdbc.config


tx Defines the elements used in the Spring Framework's declarative transaction management infrastructure. spring-tx-3.0.xsd
mvc spring-mvc-3.0.xsd
util spring-util-4.0.xsd
task spring-task-4.2.xsd


Spring Retry


Common Spring Boot Application Configuration


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

  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

  port: 8080

  secret: javainuse

spring: foo-bar
    active: local
  main.allow-bean-definition-overriding: false
      enabled: always  #
      max-file-size: 100MB
      max-request-size: 100MB

  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).
    name: boot
    password: boot

spring.profiles: local

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

  org.hibernate.SQL: DEBUG
  org.hibernate.type: TRACE

  jackson.serialization.INDENT_OUTPUT: true

    show_sql: true
    format_sql: true
    use_sql_comments: true

  enabled-by-default: true
  shutdown.enabled: false
  web.exposure.include: "*"
  jmx.exposure.include: "*"

    url: http://localhost:8080
  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()
 1 public class SearchTaskProcessorTest{
 3   //...
 4   ConfigurableApplicationContext spring;
 5   private SearchMasterMapper masterMapper;
 6   private SearchDetailMapper detailMapper;
 7   private SearchRoiMapper roiMapper;
 8   private SearchRoiParamMapper roiParamMapper;
 9   private SearchRoiPointMapper roiPointMapper;
11   @BeforeClass
12   public void beforeClass() throws Exception{
14     //...
15     this.spring = new ClassPathXmlApplicationContext(CONFIG_LOCATION);
16     this.spring.registerShutdownHook();
17     this.masterMapper = this.spring.getBean("searchMasterMapper", SearchMasterMapper.class);
18     this.detailMapper = this.spring.getBean("searchDetailMapper", SearchDetailMapper.class);
19     this.roiMapper = this.spring.getBean("searchRoiMapper", SearchRoiMapper.class);
20     this.roiParamMapper = this.spring.getBean("searchRoiParamMapper", SearchRoiParamMapper.class);
21     this.roiPointMapper = this.spring.getBean("searchRoiPointMapper", SearchRoiPointMapper.class);
22   }
24   @AfterClass
25   public void afterClass(){ }
27   @Transactional
28   private SearchRequest createAndPersistNewSearchReq(){
30     //...
31     this.masterMapper.insertSearchMaster(req);
32     this.detailMapper.insertSearchDetail(req.getId(), cctv);
33     this.roiMapper.insertSearchRoi(req.getId(), cctv.getSystemId(), cctv.getId(), roi);
35     for(Param param: roi.getParams()){
36       this.roiParamMapper.insertSearchRoiParam(req.getId(), cctv.getSystemId(),
37         cctv.getId(), roi.getNo(), param);
38     }
39     for(Point pt: roi.getPoints()){
40       this.roiPointMapper.insertSearchRoiPoint(req.getId(), cctv.getSystemId(),
41         cctv.getId(), roi.getNo(), pt);
42     }
44     return req;
45   }
47   @Test
48   public void testProcess(){
50     SearchRequest req = this.createAndPersistNewSearchReq();
51     SearchTaskProcessor processor = this.spring.getBean(...);
53     //...
55     processor.process(req.getId(), "1", crtr);
56   }
57 }

In proxy mode
  • Log
Community content is available under CC-BY-SA unless otherwise noted.