Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Monday, 28 June 2021

Spring JPA Query

in construction

Spring Data JPA  Queries 

  • Derived query, a method signature query
  • @Query including JPQL or Native SQL 
  • DSL query: type-safed, compiling time error checking 
  • Projections: interface-based(closed projections or open projections); class(DTO)-based

Derived Query (Simple Query Method Signature )

This method is applied on the entity level. 

a. return type; b. friendly; c. Entity AttributeName(camelCase) d. query parameters matching entity attribute type

The query method can span multiple nested entities, chaining the attribute names and following the camelCase rules. 

List findByPersonAddressCity(String city); 

filters and, LessThan, GreatThan, Contains, Like, containing(string) IgnoreCase; between(a value and b value);  Sort the attributes: OrderBy;

Error reporting: Spring Data JPA facilitates fast failure; it avoids the errors that are thrown in the runtime. 

If the property is misspelled, getting a PropertyReferenceException: no property X found for type Y.  

@Query method

When the query method signature becomes over-complicated, it may be using @Query decorated on the top of a repository method; it could be a JPQL query or native SQL query.  Queries declared by @Query on the top of repository interface methods, take precedence over the named queries.

By default, JPA using position-based parameter binding.  Using named parameter in the query, rather than parameter positioning, ': name' ref. by '@Param("name")', may make the query less error-prone. 

DSL(dynamic query)

sort can be done providing sort or pageable.

Sort sort = new Sort(Sort.Direction.Asc, "title);
bookRepository.findByTitleContains("Hibernate",sort)

Limit the number of results.
findFirst5By

Pagination

Pageable

PageRequestOf.


Projection Types

Instead of using an Entity projection, returning the whole of aggregate root and/or its dependencies; projections may limiting the amount of returned attributes from a database query to what we need; it may optimize the underlying generated SQL query, reducing the query operations on the database and therefore improve the DB performance. 

    Interface-based projection

    Spring relies on the interface to create a proxy to wrap an entity so as to modify the entity behaviors.

    closed projection

    a closed projection means a method name exactly matches an attribute name.

    a constrain: the closed projection interface is only used as an element type of a collection.

    a closed project may carry out a nested projection, but it must root on the owner side, otherwise, on the inverse side, it doesn't have a reference to the nested entity.

    open projection

    An open projection decorated with SpEL enables us to define interface methods with unmatched names and with return values re-computed at a runtime.

    drawback: its query is created during the runtime, so Spring cannot optimize the query in the advance.


    Class-based projection

    instead of defining interfaces and allowing Spring to create proxy around them, we may create our own classes to project from the root entity via the repository.

    a constraint: the class overrides hashcode and equal(the class may be handled in a collection); constructor parameter name must be the same as the counterparts declared in the root entity.


    Dynamic projection

    a root entity is queried through a repository, it may have different views; the dynamic projection offers a genric way to combine the root entity and its views in one query method.

    <T>  List<T> findByLastName(String lastName, Class<T> class); 




    Reference

    Spring Data JPA Tutorial: Creating Database Queries From Method Names

    @Query Annotation in Spring Data JPA

    Thursday, 25 February 2021

    Configuring Spring Boot Test

    In construction.

    Spring test annotations: 

    @SpringBooTest

    @DataJpaTest

    @TestPropertySource

    @ActiveProfiles

    @Sql


    @SpringBootTest

    It is used for an integration test and loading the entire application context. Through the attribute classes, you may specify the classes and narrow down the scope of the application context. There is another important attribute, webEnviornment, which may specify the type of web application context and also we may turn it off for some tests which do need a web context, so as to lighten the test. 

    @TestPropertySource

    In some cases, we may need specific properties for a test, by overriding the properties defined in the src resources or by adding new properties. You have two ways to specify test-specific properties.  @TestPropertySource is applied at the class level, and loading a property file for the current test from the classpath by default, or from a specific location. Rather than loading a test property file, using @ActiveProfiles("test")  to activate a specific profile, it may bring in a profile-specific property. meanwhile, It offers an inline way to set properties, to set property-value pairs.  

    @SpringBootTest
    @TestPropertySource("classpath:mytest-application.properties")
    @Slf4j
    class LinearRegressionApplicationTests {
    @Value("${my.math}")
    private boolean myMath;

    @DataJpaTest 

    It is an annotation that tailors the application context enough to test a repository. All beans above the repository will not be created, but only relevant ones for the current test.  

    A feature of @DataJpaTest, it activates an embedded database and disabling other data sources. In this case, if your project by default is using a real database, then you need to disable auto-configuring embedded database

    @DataJpaTest
    @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)

    @ActiveProfiles("dev") only trigger the bean data-source active. this is why application-dev.properties are not activated by @ActiveProfiles("dev").  

    Configuring Spring boot test with different Data Source

    When a Spring boot project has multiple data-source, @DataJpaTest may fall in an error, loading application-Context failure. 


    @Sql

    It is used to annotate the test class or test method, to run a SQL script against a given database. The scripts can be configured to run before the method or after the method. 

    @DataJpaTest
    @Sql("classpath:insert-data.sql")
    @Sql(scripts = {"classpath:delete-test-data.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
    class PersonRepoTest {

    @Autowired
    private PersonRepo personRepo;

    @DataJpaTest
    @Sql("classpath:insert-data.sql")
    @Sql(scripts = {"classpath:delete-test-data.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
    class PersonRepoTest {

        @Autowired
        private PersonRepo personRepo;


    @SqlMergeMode

    @SqlMergeMode is used to annotate a test class or test method to configure whether method-level @Sql declarations are merged with class-level @Sql declarations. If @SqlMergeMode is not declared on a test class or test method, the OVERRIDE merge mode will be used by default. With the OVERRIDE mode, method-level @Sql declarations will effectively override class-level @Sql declarations.

    @SqlConfig

    @SqlConfig defines metadata that is used to determine how to parse and run SQL scripts configured with the @Sql annotation. The following example shows how to use it:

    configure different data-source for test


    @ContextConfiguration

    @ContextConfiguration loads an ApplicationContext for Spring integration test. @ContextConfiguration can load ApplicationContext using XML resource or the JavaConfig annotated with @Configuration. The @ContextConfiguration annotation can also load a component annotated with @Component, @Service, @Repository etc.



    Monday, 11 January 2021

    Understanding Spring and Config It

    Spring Framework

    Spring is built on the top of JEE. It re-manage the usage of JEE API and releasing developers from some trivial works.

    Init a minimal spring project that needs the following major dependencies: 
    spring-context: defines the actual Spring Injection Container and has a small number of dependencies: spring-core, spring-expression, spring-Aop, and spring-beans.
    spring-core: is the core framework that provides the container required to implement Dependency Injection and inversion of control.

    Application context:

    ApplicationContext is a sub-interface of BeanFactory; so it is also a BeanFactory. In addition, it needs to know some concepts, Inversion of Control(IOC) and IOC container, Dependency Injection(DI),  and bean metadata.  The concept of IOC is about who is going to drive the car; driving yourself, or hiring a driver driving for you. That is the inversion of control. In another word in the software, who is going to inject the dependencies; injecting yourself, or leaving a container injecting for you. We leave the controls of creating an instance and its dependencies to a container, so as to dissolve client code from coupling with the underlying dependencies. 

    The application context acts as the heart of the Spring framework. It encapsulates the bean factory,  and loading bean metadata externally for bean creation;  it provides a mechanism for the creation of beans in the correct order, meanwhile providing all beans dependency injections;  beans are created as the application startup, and managed in an IOC container ready for providing bean reference when the code request for it.

    Developers mainly config IOC container and leaving bean creations to the container. By this way, it decouples class dependencies and leaving all of these couplings within the container. We use a kind of metadata or whatever it is called to tell the IOC container which beans are needed and their dependencies, just like a blueprint that depicts how an instance is created.  For the client-side code, it uses the @Autowire to request IOC container at the point it needs an instance reference. It means that the IOC container needs to provide the instance reference and assemble its all dependencies, i.e. it is also called Dependency Injection(DI)


    DI and IOC container:  

    Injection means that at a point that the code needs to refer to an instance, it requests the container and achieves its reference. All DI is handled by the bean factory, which is in charge of figuring bean dependencies, and in charge of assembling all these beans together and return the root reference to the client.  

    IOC container manages dependent classes and their instances in a graph. It wires all class dependencies once and re-uses it as any point.  It, therefore, reducing a lot of repeated work and removes the coupling of classes from the client code.

    DI and IOC are carried by two Spring packages, i.e. Spring core and Spring context. At a minimum, if you include these two packages in your project, then you may implement DI.

    Configuring Application Context

    Configuring Spring differently for different deployments, which may include different beans, different properties, different databases etc.

    We looked at multiple ways of activating profiles. Let's now see which one has priority over the other and what happens if you use more than one, from highest to lowest priority:

    1. Context parameter in web.xml
    2. WebApplicationInitializer
    3. JVM system parameter
    4. Environment variable
    5. Maven profile 

    Profiles:

    @Profile is applied with @Configuration or individual bean method level.

    @Profile("!dev")
    @Bean

    Spring Core Property together,  i.e. spring.profiles.active = 'dev', indicates that the 'dev' profile is activated. It realises that the configurations, beans, or properties can be switched according to the activated profile.

    It is able to activate a @Profile externally during application start-up.

    JVM system parameter:
    -Dspring.profiles.active=dev

    Program argument:
    spring.profiles.active=dev

    Environment variable:
    in UNIX: export spring_profile_active=dev
    or in IDE edit Configurations: set Environment variable; spring.profiles.active=dev

    Application property file:
    spring.profiles.active=dev

    Command line parameter:
    java -jar any.jar --spring.profiles.active=dev

    Spring profile can be activated via Maven profiles, by specifying spring.profiles.active configuration property.

    ref. to https://www.baeldung.com/spring-profiles

    Using @ActiveProfile in Tests, making it easy to specify what profiles active.

    Value injection: 
    @Value is used for injecting property into the code. It is used in the fields or method arguments.
    It may inject a value object from a property file or system or environment variables.

    Spring expression language(SpEL) 

    SpEL is an expression language that supports querying and manipulating an object graph at runtime. It is a single well supported within the Spring community, but it is self-contained and can be used independently. SpEL supports calling methods, accessing properties, and calling constructors.

    We often use SpEL for Annotation Configuration; like putting a default value on fields, methods, and method or constructor parameters. 
    @Value("#{new Boolean(environment['spring.profiles.active']!='dev')}")
    private boolean is24Hours;
    Spel can do a logic operation, may be helpful.

    https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#expressions

    Proxies

    Proxy is a pattern, it is used to add behaviours to classes. Spring uses a lot of proxies to add aspected behaviours, for instance, transaction boundaries, security check,  logging, cache etc.  

    Spring uses both JDK and CGLib-based proxies in its operations. JDK uses an interface to generate a proxy class in order to wrap the target class, but CGLib extends directly from the target class and overriding the point-cut. 

    Bean Scopes

    Bean scopes are critical concepts for understanding Spring in depth.

    • Singleton:  By default, all classes decorated by @Component are instantiated as a singleton, namely one instance per spring application context.  It needs to watch out states shared across the user of the bean.
    • Prototype;  Bean definition stored in IOC;  new instance every time it is referred. The definition is stored in IOC.
    • Session: It applies to web environment only. Session scope means one instance of a bean per user session.  Definition of the bean is stored in an IOC container when a session is created, the bean is created.
    • Request:  It applies to web environment only. Within a user session, the user may trigger several HTTP requests. A request scoped bean has a life cycle as the request where it is spawned.

    Component Scanning

    There are three ways to provide bean factory blueprints, i.e. an XML file, Java-based config, or Component scanning. Today, component scanning is the favourite for defining bean metadata. 

    Component scanning(@ComponentScan) scans a base package(com.xxx.xxx) and load classes decorated by @Component or its derivatives(@Service, @Repository, etc) into the bean factory.  @ComponentScan without arguments tells Spring to scan the current package and all of its sub-packages.

    Using @ComponentScan annotation along with @Configuration annotation together may bring Java-based blueprints and Component scanning metadata together to BeanFactory via an ApplicationContext.

    In SpringBoot, using @SpringBootApplicatoin includes the component scanning by default. @ComponentScan(basePackages="xxx.zzz.yyy") defines the entry to scan for components.  Properties file can be scanned and loaded @PropertySource("classpath: application. properties"), it externally defines a location of customer property files

    In a component scanning process, it builds up the dependency graph automatically according to component dependencies,  also called Dependency Injection(DI). From the client-side of beans, it is referred to as an auto-wiring process using @Autowired annotation at the point that the code needs the reference of the instance. IOC container and DI build up bean graph for clients and can be reused many times afterwards. This is a big saving. 

    Using @Qualifier or @Primary to solve type ambiguity, because of one type having more than one implementation.

    Component scanning is also used with conditional configuration.

    Lifecycle methods: 

    Leveraging JSR-250, not Spring specific. 

    Post Construction (@PostConstruct) means to do something before a bean become use phase. It must be a void method without arguments. It is called after property setting is completed. it is used to init.

    Pre Destroy(@PreDestroy) means to do something before the application context closes. The method is called before the application context is about to remove the bean. The method may be used to close the opened resources.

    Both of them not included after java 9. 


    Bean Life Cycles

    There are three phases, initialization, use(interacting with Spring IOC container), and deconstruction. The most time of life cycle is spent during the use phase; the most complicated phase is the initialization, and deconstruction is the end of the life cycle. The following diagram illustrates the initialization. It begins with the creation of the application context and follows up with the bean factory initialization phase and bean initialization and instantiation. It is a phase we can impact the behaviour of application most. 

    Init phase:  creating of App context => bean factory initialization phase=>bean initialization and instantiation

    Load bean definitions: 

    Bean definition loaded: 

    The first step loading bean definition into the bean factory from all sources:
    1. Java configuration(@Configuration,@Bean,@Value, @DependsOn,@Import)
    2. XML configuration; not often used now. 
    3. Component scanning and auto-configuration. (@ComponentScan,@Component)
    You can do all of them, but the best is to pick up one and stick with it.  The bean definition (class metadata); at the point, has been loaded, and instance references are created, however, instances have not been created. It is import to know that at this phase there is no bean having been instantiated.  At this phase, the bean factory contains bean metadata. and bean references.

    Post-process bean definitions:

    BeanFactory Post-Processors: Before bean instantiation, and after bean definition loading. This phase allows modifying any bean in the factory prior to instantiation. One of the most familiar examples of this is the  PropertySourcesPlaceholderConfigurer. 

    Bean postprocess is the first extension point, allowing to impact bean factory. You can extend from the BeanFactoryPostProcessor to write a custom code to do something to beans or a subset of beans. 
    It is not common to write your won, but it is good to understand you can use this to your advantage. It is very common to use existing ones(registering scope, properties)

    Bean factory post-processors(BFPP) and bean definitions must be static; removing risks of side effects of dynamic instances.

    At the end of this stage, the bean factory is loaded with references; the bean factory and all beans are configured; all system-level work is completed in Spring; It is ready for the next stage. 

    Instantiation phase: 

    for each bean Bean factory need to do: 

    Construction

    Beans are instantiated using constructors; Done in the correct order to ensure dependencies are created first; Creating only singletons at this  point, anything other than a singleton bean will not be constructed because they are prototype or session beans;

    Eager vs. Lazy
    By default, all beans are instantiated eagerly. To truly be lazy, there can be nothing that depends on them. Even you label a bean as a lazy bean, the application context reserve the right to ignore.

    At the end of this phase, bean reference is still kept inside the Bean Factory; instances have been constructed, but not ready for use yet.

    Setters:

    post-initialization DI should only be done on optional beans or dynamic beans.
    Autowiring occurs(non-constructor based)

    This is another chance to auto-wire after beans having been instantiated.  Autowiring occurs on setters with @Autowired  annotation. 

    At the end of this phase, all dependencies are injected, beans are fully initialized, but still not ready for use.

    Bean post-processor(pre-initializer)

    This is the final point of configuration manipulation. each bean may have additional behaviours added at this point; the bean post-processing event. there are two types of extensible and generic processing: before and after initializer.

    Initializer: 
    This is the second BeanPostProcessor action. @PostConstruct methods called here.

    many other things happen during this initializer phase. 

    BeanPostProcessor Interface
    The bean post-processor interface is used for pre or post initializer steps. The BeanPostProcessor interface allows you to inject common behaviour to a "class" of beans. It still operates on specific beans.  The framework leverages lots of these, a lot of proxies are built during this pre-phase especially.  



    Bean post-processor(Post-init)
    at the end of this phase, beans have been instantiated and initialized.
    Dependencies have been injected.
    Beans are finally ready for use.

    Use phase:

    Most time is spent in this phase; ApplicationContext serves proxies to the original class; ApplicationContext maintains handle to each bean(singleton)

    context-aware beans
    Spring provides interface ApplicationContextAware; gives your class a handle to the ApplicationContext; not a very common interface to use, but is available during the use phase.
    Actually, the context-aware beans get an application context reference injected.

    https://dzone.com/articles/spring-bean-lifecycle-using-spring-aware-interface


    Destruction phase:

    When close is called on the ApplicationContext, the destruction phase of the life cycle begins, and it is a one-way door. Any @PreDestroy method is called at this point, in which beans are not destroyed, but only destroyed by GC.


    Aspect-Oriented Programming

    An Aspect stands for a cutting concern across many classes, and it is important to know AOP change your code behaviour in the runtime, only in the runtime. 

    AOP is for reusing code on a cutting-cross concern, fx: logging, transaction management, caching, security, checking method performance, handling common exceptions etc. AOP programming is an easy way of applying the same code in many classes, to extend or modify its existing method's behaviour. 

    In Spring, AOP is implemented by a JDK dynamic proxy(AspectJ) or a CGLIB proxy(inheritance).  AOP is implemented as a proxy pattern or OOP inheritance. 

    Dependencies: 
    spring-core, spring-context, and aspectjweaver 

    Concept and Terms:

    In the Spring, basically, AOP concept/terms/annotations have one to one mapping relationship; exactly understanding terms help to implement AOP in the code.  
    • Primary concern: business logic
    • Secondary concern: a supportive function. 
    • Weaving: linking Aspect with other application types or objects to create an advised object. 
    • Target object: object being advised by one or more aspect; referred to as the advised object. 
    • Joinpoint: a spot in your BL code, where a cutting concern code can be applied there.
    • Pointcut: selecting a joint point to apply a common-concern code that matches join points. 
    • Aspect: a concern that cuts across multiple class. 
    • Advice: an implementation of Aspect. the code to solve the cutting concerns
    • AOP proxy: a proxied target created by the AOP framework, to carry out the Advice.
    The major points as Implementing an AOP: 
    You need to define JoinPoint and then using PointCut to select the JoinPoint, Afterwards implementing the cutting concern code in an Advice. 


    Pointcut syntax:

    designator("r p.c.m(arg)") 
    r:return type; 
    p:package; 
    c: class; 
    m: method; 
    arg:args

    Supported Pointcut Designators

    Spring AOP supports the following AspectJ pointcut designators (PCD) for use in pointcut expressions:

    execution: For matching method execution join points. This is the primary pointcut designator to use when working with Spring AOP.

    within: Limits matching to join points within certain types (the execution of a method declared within a matching type when using Spring AOP).

    this: Limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type.

    target: Limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type.

    args: Limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types.

    @target: Limits matching to join points (the execution of methods when using Spring AOP) where the class of the executing object has an annotation of the given type.

    @args: Limits matching to join points (the execution of methods when using Spring AOP) where the runtime type of the actual arguments passed have annotations of the given types.

    @within: Limits matching to join points within types that have the given annotation (the execution of methods declared in types with the given annotation when using Spring AOP).

    @annotation: Limits matching to join points where the subject of the join point (the method being run in Spring AOP) has the given annotation.



    You need to enable AOP @EnableAspectJAutoProxy
    Enables support for handling components marked with AspectJ's @Aspect annotation, similar to the functionality found in Spring's <aop:aspectj-autoproxy> XML element. To be used on @Configuration classes 

    Using @Aspect to define an Aspect, but must together with a @Component, so that @Component can detect it. 

    Type of Advice:

    • Before advice:  advice executed before a joint point.
    • After returning advice: Advice to be executed after a join point completes normally.
    • After throwing advice: Advice to be executed if a method exits by throwing an exception.
    • After(finally)  advice: Advice to be executed regardless of means by which a join point exits(normal or exceptional return).
    • Around advice:  performing custom behaviour before and after the joinpoint.

    Sunday, 20 December 2020

    Spring annotations


    @Component is added at a class, meaning that this class will be scanned by the Spring container and loaded in the Spring context.  @Component is the most generic decoration. A @Service is a component; A @Controller is a component too. 

    @Service means actually a specific @Component, which stands for a business logic layer.  So when a class is added with @Service, it will be scanned by Spring container and loaded in the context. 

    @RestController  is also a specific @Component when a Spring context is initiated. These controllers will be instantiated and start waiting for the requests and making responses. 

    @Autowired is specific to the Spring framework; it is equivalent to the Java @Injected 

    @Configuration and its Relevant Annotations


    @Configuration working with @Bean, @Value, @PropertySource, @ComponentScan and @Profile

    @Configuration together with @Bean defines a bean blueprint, which tells a bean factory how to create a bean and its dependencies(DI).  In a simple word, it depicts a bean graph. 

    @Configuration indicates a class, in which one or more @Beans methods are declared. 

    What is a @Bean? @Bean is used to decorate a method. It tells Spring that this method is used to return an instantiated  @component or @Service. @Bean is used together with @Configuration class to tell Spring framework how to do DI. 



    @Cofiguration working with externalized values

    @Configuration class may need external env properties or other values defined in the other property files. 

    Using  Environment API

    Via Spring Environment injection, we may access properties. 
    @Configuration
     public class AppConfig {
    
         @Autowired Environment env;
    
         @Bean
         public MyBean myBean() {
             MyBean myBean = new MyBean();
             myBean.setName(env.getProperty("bean.name"));
             return myBean;
         }
     }

    Using Property Sources

    Properties resolved via Environment reside in one or more "property source" objects; @Configuration may work with specific property files. 
    @Configuration
    @PropertySource("classpath:/com/acme/app.properties")
     public class AppConfig {
    
         @Inject Environment env;
    
         @Bean
         public MyBean myBean() {
             return new MyBean(env.getProperty("bean.name"));
         }
     }

    Using Value Injection

    Without bypass the Environment, externalized values may be injected into @Configuration via @Value.
    @Configuration
     @PropertySource("classpath:/com/acme/app.properties")
     public class AppConfig {
    
         @Value("${bean.name}") String beanName;
    
         @Bean
         public MyBean myBean() {
             return new MyBean(beanName);
         }
     }

    Specifying @Component Location

    @ComponentScan configures component scanning directives for use with @Configuration classes. 

    @Configuration
     @ComponentScan("com.acme.app.services")
     public class AppConfig {
         // various @Bean definitions ...
     }


    ?About proxyBeanMethods

    By default  @Configuration(proxyBeanMethods=true); it specifies whether @Bean methods should get proxied in order to enforce bean lifecycle behaviour, e.g to return shared singleton bean instances even in direct @Bean method calls in user code. This feature requires method interception, implemented through a runtime-generated CGLIB subclass which comes with limitations such as configuration class and its methods not being allowed to declare final.  
    public abstract boolean proxyBeanMethods


    Sunday, 18 October 2020

    Adding Extra Property Files in Spring and SpringBoot

    Register a Properties File via Java Annotations

     @PropertySource annotation, it is introduced since Spring 3.1, and used in conjunction with Java-based configuration and the @Configuration annotation. 


    Another useful way to register a new properties file is by using a placeholder, which allows us to dynamically select the right file at runtime. 

    ${envTarget:mysql}


    Defining Multiple Property Locations

    The  @PropertySource annotation is repeatable according to Java 8 conventions. We can define multiple properties files and their locations. 

    We can specify an array of @PropertySource; this works in any Java version.

    Using/Injecting Properties

    Injecting a property using the @Value annotation.

    ?? specify a default value for the property. 

    We can obtain the value of a property using the Environment API
    @Autowired
    private Environment env; 
    ...
    dataSource.setUrl(env.getProperty("jdbc.rul));


    Properties with Spring Boot

    Default Property File


    This new support involves less configuration compared to standard Spring. 

    application.properties: the Default Property File; doesn't need any arrangement


    Environment-Specific Properties File

    If we need to target different environments, application-environment.properties file in the src/main/resources directory, and then set a Spring profile with the same environment name. 

    if we define a "staging" environment, we then have to define a stagging profile, and then application-stagging.properties. 

    This env file will be loaded and will take precedence over the default property file. 


    Test-Specific Properties File

    Spring boot looks for test specific files in our src/test/resources directory during a test run. Again, default properties will still be injectable as normal but will be overridden by these test specific properties if there is a collision. 


    @Runwith(SpringRunner.class)
    @TestPropertySource("/foo.properties")


    if we don't want to use a file, directly specify names and values.
    @TestPropertySource(properties={"foo=bar"})

    or it can achieve the same using
    @RunWith(SpringRunner.class)
    @SpringBootTest(
    properties={"foo=bar"},classes=SpringBootPropertiesTestApplication.class)
    )


    Hierarchical Properties

    we can mapping a group of properties from a file into a POJO, using @ConfiguartionProperties annotation.

    Properties from Command Line Arguments

    java -jar app.jar --property="value"

    or via system properties, which are provided before the -jar command rather than after it
    java -Dproperty.name="value" -jar app.jar

    Properties from Environment Variables

    export name=value
    java -jar app.jar







     




     



    Tuesday, 7 July 2020

    Configuring Integration Tests

    @ContextConfiguration

    It is a class-level annotation, used to determine how to load and configure an AppplicationContext. Actually, it creates a customed application context for this specific integration test. It loads @Configuration and @Component for a specific integration test. 

    @ActiveProfiles

    It is a class-level annotation that is used to declare which bean definition profiles should be activated when loading an ApplicationContext for an integration test. 
    Activating a @Profile for this integration test. 

    @TestPropertySource

    It is a class-level annotation, used to configure the location of properties files for an ApplicationContext loaded for an integration test.  

    Loading a specific property file for this integration test.


    @Sql 
    It is used to annotate a test class or a test method to configure SQL scripts to run against a given database during integration tests. 

    By default, the SQL script is carried before the test method; but it can be configured by @Sql parameter. 




    Tuesday, 26 May 2020

    Command-line Runner vs Application Runner

    They both may be useful for writing init, admin tasks. 

    We use Command-line runner interface to wrap a set of work, and bring it into the Spring boot, and let it is carried out immediately after the application context is all up and running. We may inject application arguments into a command-line run method. We may have more than one command-line runner in one spring boot application and their orders can be controlled by an annotation @Order.  Otherwise, Spring will select a default order for them.

    ApplicationRunner is a cousin of Command-line runner. 

    Saturday, 11 April 2020

    Spring Mvc

    Spring Web MVC

    Spring web MVC is built on the servlet API and has been included in the Spring framework from the very beginning. The formal name, "Spring Web MVC", comes from the name of its source module(spring-webmvc), but it is more commonly known as "Spring MVC"

    Servlet means Server Component. Here, the let means component.

    Spring MVC follows the front controller pattern, which stands for the core of the framework. It accepts the Http requests from the clients and mapping them to the corresponding handlers(controllers),  which are also servlets.

    DispatcherServlet

    Spring MVC is designed around the front controller. It is a central servlet, i.e. dispatcher servlet, which provides a shared algorithm for request processing. However, actual works are performed by configurable delegators. This model is flexible and supports diverse workflows.

    DispatcherServlet works like web.xml to mapping the request to its handler. Meaning that web.xml defines the mapping to locate the resource.


    Traditionally, the developer needs to tell Spring container to bootstrap a servlet dispatcher by implements WebApplicationInitializer, where we may tell the container to instantiate a dispatcher servlet in the highest priority, meanwhile designating a specific WebApplicationContext, for instance, an AnnotationConfigWebApplicatoinContext. WebApplicationInitializer implementations are detected automatically, so you may package them within the application as you see fit. 

     public class MyWebAppInitializer implements WebApplicationInitializer {
    
        @Override
        public void onStartup(ServletContext container) {
          XmlWebApplicationContext appContext = new XmlWebApplicationContext();
          appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
    
          ServletRegistration.Dynamic dispatcher =
            container.addServlet("dispatcher", new DispatcherServlet(appContext));
          dispatcher.setLoadOnStartup(1);
          dispatcher.addMapping("/");
        }
    
     }

    In the above, WEB-INF/web.xml was replaced with code in the form of a WebApplicationInitializer, but the actual dispatcher-config.xml Spring configuration remained XML-based. This can be configured in a 100% code-based approach. 

     public class MyWebAppInitializer implements WebApplicationInitializer {
    
        @Override
        public void onStartup(ServletContext container) {
          // Create the 'root' Spring application context
          AnnotationConfigWebApplicationContext rootContext =
            new AnnotationConfigWebApplicationContext();
          rootContext.register(AppConfig.class);
    
          // Manage the lifecycle of the root application context
          container.addListener(new ContextLoaderListener(rootContext));
    
          // Create the dispatcher servlet's Spring application context
          AnnotationConfigWebApplicationContext dispatcherContext =
            new AnnotationConfigWebApplicationContext();
          dispatcherContext.register(DispatcherConfig.class);
    
          // Register and map the dispatcher servlet
          ServletRegistration.Dynamic dispatcher =
            container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
          dispatcher.setLoadOnStartup(1);
          dispatcher.addMapping("/");
        }
    
     }

    In the Spring boot, the dispatcher servlet doesn't need to be initialized but auto-generated by the Spring container.

    Whatever the ApplicationConfig is required, it extends from WebMvcConfiguartionSupport, which implements ApplicationContextAware and ServletContextAware. Because the Aware interface, Application context will transfer back its instance to the WebAMvcConfigurationSupport. This is the main class providing the configuration behind the MVC java config. It is typically imported by adding @EnableWebMvc to an application @Configuation class.

    Within ApplicationConfig, we need to define InternalResourceViewResolver, which declares ①viewClass=org.thymeleaf.spring5.view;②prefix=/resource/templates/ ;③ suffix =.html
    They are all resources but located inside the project. That is why it is called Internal resources. The view class is dependent on which view technique is applied in the project; the prefix is put before the logic view name, and the suffix is put after the logic view name; so that they together form a directory tree.

    InternalResourceViewResolver is the most popular view-resolver, but there are other variants.

    Special bean types:

    • HandlerMapping: maps request to the handler.
    • HandlerAdapter: invokes a handler.
    • HandlerExceptionResolver: helps with exception handling.
    • ViewResolver: helps resolve views.
    • LocaleResolver: helps for l10n and i18n support. 
    • ThemeResolver: helps with stylized look and feel

    Java-Based config:

    We can now do completely in Java what used to be done in web.xml and Spring bean definition XML files.
    • Web application initializer
    • Root application context configuration
    • Dispatcher no.1 config: /main/*
    • Dispatcher no.2 config:/api/*

    Controller

    Controller Types:  @Controller and @RestController
    @RestController only return @ResponseBody; but@Controller returns view(a logical string) and model.

    Controller methods decorated by @RestMapping are handlers, which response the request from the clients.

    Request mapping by:

    • URI pattern with @PathVariable
    • @RequestParameter and parameter condition
    • @ModelAttribute: binding form fields to the java POJO attributes 

    Method input arguments:


    25 supported

    Method return values:

    15 supported


    Data Binding

    Collecting data from view fields and binding them into java object, or in another way around, the java data model that is fetched from the controller, and then presented on the view (Html and JSP page)

    From a view to a controller:

    @ModelAttributes can be used at the method level or method parameter level.

    When @ModelAttributes used at the method level. it is always called before any request handler(controller method decorated by a request mapping); meaning that, any model required has to be created before any request handler that can be carried out. This is used to instantiate models and giving them default values.

    When @ModelAtrtributes used at the method parameter level, a form of a view can be bound into a java POJO model.

    From controller to view: 

    The model can supply attributes used for rendering views. To provide a view with usable data, we simply add this data to its Model object. It is used as a Map, storing the data with a key. The Model can be directly injected from the controller method argument.

    Data Validation:

    Data could be polluted in the views as reaching the controllers. so it needs to be validated.

    Spring validator interface for application-specific objects.
    JSR 380(javax.validation) bean validation API is the standard. It goes well with Spring 5.1.

    Using annotations to add validation rules on java bean attributes. Then the Spring framework will do validation for us.

    Using annotation @Valid to Enable validation in the Controller method argument. The validation result is contained a BindingResult parameter, which must be declared immediately after the validated target.

    Data Converter

    For Http requests, string-based values are extracted from the request including request parameters, path variables, request headers, and cookie values. They may need to be converted to the target type of the method parameter or field they are expected to. 

    method parameters and type conversion

    Binder methods:

    Data transferred from the view normally in strings. @ModelAttribute can do field-to-attribute binding, mapping a string to string. In a case, binding a string to a specific java type, we have to declare a binder-method, which is used to register an object conversion or formating within a controller or globally across a group of controllers.

    @InitBinderpublic void initBinder(WebDataBinder binder){
        binder.registerCustomEditor(Date.class, "dateOfBirth",   
        new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));}

    @InitBinder method  is applied to the request parameter data, URI variables, and form beans
    customizing data binding with @InitBinder
    • Bind request parameters(that is, form or query data) to an object(model)
    • Convert String-based request values(request parameters, path variables, headers, cookies, and others) to the target type of controller method arguments.
    • Format model object values as String values when rendering HTML forms.

    Exception Handling 

    • Handled by DispatcherServlet
    • Delegates to handlerExceptionResolver beans
    • What does exception handling mean in an application

    Implementations for exception handling:

    • ExceptionHandlerExceptionResolver: define exception handler methods in controllers
    • SimpleMappingExceptionResolver: map each exception class with an error page
    • DefaultHandlerExceptionResolver: default which maps exceptions to error codes
    • ResponseStatusExceptionResolver: resloves customer exceptions using @ResponseStatus

    Handling exception locally in a controller scope.
     @ExceptionHandler modifies a method that should be invoked to handle an exception.

    @ExceptionHandler({FileSystemException.class, RemoteException.class}) public ResponseEntity handle(IOException ex) { // ... }



    Handling exception globally in a controller advice class.
    Applying globally and across all @RequestMapping methods when defined with an @ControllerAdvice class or @RestContollerAdvice.

    Annotating Business Exceptions with @ResponseStatus
    A business exception can be annotated with @ResponseStatus. When the exception is raised, the ResponseStatusExceptionResolver handles it by setting the status of the response accordingly. By default, the DispatherServlet registers the ResponseStatusExceptionResolver and it is available for use.


    Controller advice:

    It is an aspect implementation relating to common concerns of controllers. If applying @ExceptionHandler, @ModelAttribute, and @InitBinder globally across all controllers, then you need to declare then within the class decorated with  @ControllerAdvice or @RestControllerAdvice.

    The controller advice class is applied on every request, every controller; meanwhile, it allows to specify certain types of controllers(@Controller or @RestController), only for certain packages,  or specific controllers. @ControllerAdvice(assignableTypes={A.class,B.class}). 

    On startup, the infrastructure classes for @RequestMapping and @ExceptionHandler methods detect Spring beans annotated with @ControllerAdvice and then apply their methods at runtime. Global @ExceptionHandler methods (from a @ControllerAdvice) are applied after local ones (from the @Controller). By contrast, global @ModelAttribute and @InitBinder methods are applied before local ones.

    Async Request Processing

    The request may be blocked due to a heavy task, which takes a long time to process.  Async request processing use Thread-1 to response Http Request thread, subsequently it uses Thread-2, which is A task executor thread in a thread pool, to handle the blocking task. The controller returns Callable or DeferredResult. 

    Set the Mvc async processing flag to be true, so as to enable the async processing. Spring boot enables async-request processing by default. So, we don't need concern about this.

    Configuring async processing in web-mvc-configuration: ➊ declare async task executor bean; ❷ set task executor within the asyncSupportConfigurer.

    @Override
    protected void configureAsyncSupport(AsyncSupportConfigurer asyncSupportConfigurer) {
        asyncSupportConfigurer.setDefaultTimeout(10000);    
        asyncSupportConfigurer.setTaskExecutor(mvcAsyncTaskExecutor());}
    
    @Bean
    public AsyncTaskExecutor mvcAsyncTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();    
        threadPoolTaskExecutor.setThreadNamePrefix("hplusapp-thread-");    
        return threadPoolTaskExecutor;}


    View Resolver

    The view resolver provides a mapping between view names and actual views.  The controller returns a view name in a string. According to the name, view resolver picks up the view template from a pre-defined folder, and then return to the client as an HTTP response.

    There are many types of view resolvers:

    InternalResourceViewResolver is used to pick up the JSP template in a correct folder in the project.
    this is used to map a view name to its JSPs.

    Employing a properties file to resolve views, which is done by a ResourceBundleViewResolver.
    Meaning that defining all view names and map it to the correct JSPs in a properties file.

    XmlViewResolver: implementation of ViewResolver that accepts a configuration file written in XML with the same DTD as Spring's XML bean factories.


    VelocityViewResolver/FreeMarkerViewResolver
    Convenient subclass of UrlBasedViewResolver that supports FreeMarkerView and custom subclasses of them.


    Interceptor 

    The concept of interceptions in Spring MVC is very similar to the filter components in the Servlet JSP API, which is used for pre- and post-processing of the request.


    Built-in and customer interceptors

    • ThemChangeTnterceptor
    • LocalChangeInterceptor
    • Custom interceptors should extend HandlerInterceptorAdaper

    Custom interceptors need to be registered in WebConfig class that implements
    WebMvcConfigurerSupport

    @Overrideprotected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoggingInterceptor()).addPathPatterns("/*");    
        registry.addInterceptor(new ThemeChangeInterceptor());}

    Session

    A session may link several controllers.

    @SessoinAttributes (used in class level)


    Themes 

    An application may have different themes. A theme stands for a different feel and a look of the view, which is defined by different CSS, images, icon ket, and font kit etc.

    Define theme using org.springframework.ui.context.ThemeSource.
    The default implementation is ResourceBundleThemeSource.
    ThemeResolver decides which theme to use

    • CookieThemeResolver
    • SessionThemeResolver
    • FixedThemeResolver

    Create theme properties file under the resource folder.
    In ApplicationConfig, register ThemChangeInterceptor and creating bean ThemeResolver.
    Used to refer themed keys from .properties file on the JSP. 


    L10n and i18n 

    Problem: common label or message may be fetched from a central place. Language may be presented differently in different countries.

    LocaleResolver into play
    Default implementation: AcceptHeaderLocaleResolver
    Add message properties files for different locales on the classpath.


    In spring boot defines messages-langShortName.properties
    language short name is here i8n code 
    fx: for Swedish, its short name is 'sv', and then the name for 'properties' file should be
    messages-sv.properties


    Creating message property files, key-value standing for the same label but different languages.
    Note:
    In IntelliJ, finding File Encoding file,  making sure default property file encoding is UTF-8, and also

    including the 'Global encoding' and 'Project encoding'.



    Chrome: settings: language. order preference of language


    LocalResolver and CookieLocaleInterceptor
    default key = 'locale'

    Rest Controller

    Access resource on the web; return data (ResponseEntity); MVC controller return view name;


    Injecting Custom Arguments

    When using Spring MVC you can add certain arguments to your controllers and the framework injects those arguments for you, fx: HttpServletRequest, Model, Locale, OutputStream etc.

    Spring MVC provides us with an interface designed to allow us to inject parameters to our controller methods: HandlerMethodArgumentResolver.

    Injecting custom method arguments
    Inject your custom method argument in Spring MVC using HandlerMethodArgumentResolver

    Tuesday, 8 October 2019

    Handling Security Exceptions in Spring Boot


    Actually, handling exceptions thrown in the security is different from handling ones thrown from the rest APIs, for they happens in the filters before reaching the Servlet dispatcher.

    Hence, we cannot handle security-relevant exceptions in @ControllerAdvice and @ExceptionHanlder,  it needs a different way


    Tuesday, 20 March 2018

    Spring Current Security Context



    Spring Security framework has two key context objects which an application must interact with:
    • SecurityContextHolder – SecurityContextHolder contains information about the current security context of the application, which includes detailed information about the user currently working with the application.
    • UserDetailsService – UserDetailsService is used to create a UserDetails object by implementing the single method of this interface: UserDetails loadUserByUsername (String username) throws UsernameNotFoundException
    There are four steps needed to secure a web application with a login page via the Spring Security framework:
    1. The user logs in with a name and a password. These two credentials are combined into an instance of the class UsernamePasswordAuthenticationToken. Then, they are passed to the AuthenticationManager for verification.
    2. If the username does not match the password, the BadCredentialsException is returned along with the message “Bad Credentials.”
    3. If the username and password match, it will return a populated authentication instance.
    4. The user sets a security context by calling the SecurityContextHolder.getContext().setAuthentication() method, where the object that returned from authenticationProvider.authenticate() is passed.

    Thursday, 6 July 2017

    Enable CROS at Spring


    I developed a group Rest API and deployed at Heroku; however, it cannot be invoked from another domain for violating the same origin principle. It is a kind of security setup.

    So I tried to use Spring @CrossOrigin to enable at rest controller or method level. However, it doesn't work well.

    Therefore, I switched to a classical way, where I created a filter to modify the response header in order to enable CORS. It works well now.

    In the Spring boot, a filer can be annotated as a component, thus it will be automatically picked up as the moment Spring context is initialized.

    The reason because:

    Spring MVC provides fine-grained support for CORS configuration through annotations on controllers. However, when used with Spring Security, we advise relying on the built-in CorsFilter that must be ordered ahead of Spring Security’s chain of filters.


    What is CORS

    Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served. A web page may freely embed cross-origin images, stylesheets, scripts, iframes, and videos.

    The following diagram illustrates the Spring MVC's working flow,i.e. how a request received from the client is dispatched internally to controllers and send back to the client in response.

    There is one way where we intercept all responses and modify their headers to enable CORS.





    Cross-Origin Resource Sharing (CORS)

    Spirng MVC 4 CORS Setup

    Enable CORS in Spring Boot (in a filter)

    Understanding CORS


    Spring CORS controller annotation not working

    Spring @CrossOrigin does not work with DELETE method

    Wednesday, 10 May 2017

    How to connect Postgres Database outside Heroku?

    I tried to connect to the heroku Postgres database locally in the Netbeans, but I failed.

    Open heroku "database credentials", copy the host, username, password etc into Netbeans as building a new database connection.

    It needs to add the following at the end of JDBC URL, otherwise connection will fail.
    ?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory

    ?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory


    Friday, 21 April 2017

    Spring with JUnit

    Testing Controllers

    @Runwith(SrpingRunner.class)

    Unit test
    @Runwith(SrpingRunner.class)
    @WebMvcTest(SpecificController.class)

    Integration test
    It includes all dependencies, and provides a full servlet engine behaviour; meanwhile, load @Controllers,@Services and @Repository; 

    @Runwith(SrpingRunner.class)
    @SpringBootTest(WebEnvironment =RANDOM_PORT); it provides a real servlet container. 


    @ContextConfiguration defines class-level metadata that is used to determine how to load and configure an ApplicationContext for integration tests.

    @ActiveProfiles("dev")

    @Configuration
    @Profile("dev")
    public class StandaloneDataConfig {
    @Bean
    public DataSource dataSource() {
    return new EmbeddedDatabaseBuilder()
    .setType(EmbeddedDatabaseType.HSQL)
    .addScript("classpath:com/bank/config/sql/schema.sql")
    .addScript("classpath:com/bank/config/sql/test-data.sql")
    .build();
    }
    }





    Testing Services 

    How to plan to test @Service components. It is the location of business logic, and typically the priority of the test. 

    Which type of test is needed? Unit test? Integration test? Both? 

    Every component should be involved in an integration test. 

    Not load @Controllers, Only load @Service; connecting to a real data source-test-specific or another staging. 

    @Runwith(SpringRunner.class) 
    @SpringBootTest(webEnvironment=WebEnvment.NONE) 
    It means there is no need to include a servlet dispatcher, a servlet container, and controllers for testing @Service layer.

    Difference between @Mock and @MockBean

    @Mock comes from Mockito framework; @RunWith(MockitoJUnitRunner.class)

    @MockBean comes from SpringBoot. @RunWith(SrpingRunner.class) 





    @ExtendWith(SpringExtension.class)
    Integrating Spring test context with the JUnit 5. 


    Testing Data Acess 

    There is no too much achieved from a unit test on the repository layer, so focusing on the integration test. 

    @Runwith(SpringRunner.class)

    it marks the unit test using the Junit4 framework. 

    @DataJpaTest

    it marks the test specific to the data access layer. Only loading repository components. 

    @AutoConfigureTestDatabase

    It is applied to a test class to configure a test database to use instead of any application-defined or auto-configured DataSource.

    @TestExecutionListeners

    @DatabaseSetup

    @DataJpaTest magic explained:

    • @AutoConfigureDataJpa: imports all configuration(components) needed for JPA testing. 
    • @AutoConfigureTestDatabase(replace=Replace.NONE): allow to specify what type of database is used for the test; using an embedded database or pointing to another database external or staging; or a default database already found on the classpath; 
    • @AutoConfigureTestEntityManager: allowing to access the EntityManager. 
    • @Transactional: AOP around the method scope. 
    • more ...

    DBUnit framework:

    DBUnit is another unit test framework in the Java ecosystem that focuses on aiding the ability to test data access code.
    • Created a DBUnit dataset, in XML
    • Combined features of Junit and DBUnit frameworks. 
    • Creating data scenario without creating date entity classes. 

           <dependency>
    <groupId>org.dbunit</groupId>
    <artifactId>dbunit</artifactId>
    <version>2.5.0</version>
    <type>jar</type>
    <scope>test</scope>
    </dependency>
    <dependency>
    <groupId>com.github.springtestdbunit</groupId>
    <artifactId>spring-test-dbunit</artifactId>
    <version>1.2.0</version>
    <scope>test</scope>
    </dependency>

    Creating integration test datasets: 

    Instruct JUnit to do the following:
    not load @Controllers,@Services
    Load @Repository and related dependencies
    Example:@Entity
    Load JPA testing configurations
    Load DBUnit testing configuration and dataset, in XML


    Test Suites

    Smoke Tests: tests that indicate basic system health. 

    Iteration Suite: tests that are related to a project iteration.

    Feature Suite: Tests that combine testing of several features.

    @RunWith(Suite.class)
    @Suite.SuiteClasses(
    {TestA.class, TestB.class}
    )

    The CI server test suite shows the following:
    • A systems health check
    • Example: database
    • Settled feature integration test
    • Extensible and flexible overall application architectures status check. 

    SpringBoot Test

    @SpringBootTest provides features like the followings:

    • Automatically searches for a @SpringBootConfiguration when nested @Configuration class is not used, and no explicit classes are specified.
    • Allows custom env. properties to be defined using the properties attributes.
    • Provides support for different web environment modes, including the ability to start a fully running web server listening on a defined or random port. 
    • Registers a TestRestTemplate and/or WebTestClient bean for use in web tests that are a fully running web server.

    Using @SpringBootTest for integration testing

    SpringBoot integration test: Spring framework offers a way to wire up loose coupling components within an embedded servlet container, and enabled automated configuration, which is also called the Spring Application Context. In such a sandbox, a developer may test his unit test cases(JUnit), such as sending an Http request to web-service methods and connecting to a database(maybe in memory).

    Since Spring 3.2, Spring Mock MVC framework provides a test context. It simulates a servlet container, where an HTTP request can be launched and handled by the controller. By this way, a  controller can be tested as if it is running a production server.


    In order to initiate a SpringBoot unit test, you need adding following two annotations on a test class.

    @RunWith(SpringRunner.class) it bridges JUnit 4 

    @SpringBootTest a number of other annotations are also provided for testing more specific slices of an application. The @SpringBootTest annotation tells Spring Boot to go and look for the main configuration class (one with @SpringBootApplication for instance), and use that to start a Spring application context.

    You can use the webEnvironment attribute of @SpringBootTest to further refine how your tests will run:

    • MOCK — Loads a WebApplicationContext and provides a mock servlet environment. Embedded servlet containers are not started when using this annotation. If servlet APIs are not on your classpath this mode will transparently fall back to creating a regular non-web ApplicationContext. Can be used in conjunction with@AutoConfigureMockMvc for MockMvc-based testing of your application.
    • RANDOM_PORT — Loads an EmbeddedWebApplicationContext and provides a real servlet environment. Embedded servlet containers are started and listening on a random port.
    • DEFINED_PORT — Loads an EmbeddedWebApplicationContext and provides a real servlet environment. Embedded servlet containers are started and listening on a defined port (i.e from your application.properties or on the default port 8080).
    • NONE — Loads an ApplicationContext using SpringApplication but does not provide any servlet environment (mock or otherwise).

    Using @SpringBootTest for unit testing

    'Classes' attribute:

    The classes attribute specifies the annotated classes to use for loading an ApplicationContext.
    @SpringBootTest classes attribute usage

    @SpringBootTest(classes = {EmployeeRepository.class, EmployeeService.class})
    public class SpringBootDemoApplicationTests
    {  
        @Autowired
        private EmployeeService employeeService;
        //---- tests -----
    }





    References


    Spring Boot Hello World Example – Mustache




    Can Jackson Deserialize Java Time ZonedDateTime

    Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...