Monday, August 24, 2020

Spring - AutoWiring

Spring automatically resolves the dependencies between the collaborating beans by inspecting the contents of the BeanFactory. This is called Autowiring.

Spring has 5 modes of autowiring:

1. no
    - default
    - means no autowiring
    - we have to use explicit bean reference for wiring

2. byName
    - autowiring by property name
    - The IoC container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file

3. byType
    - autowiring by property datatype
    - The IoC container tries to match and wire a property if its type matches with exactly one of the beans name in configuration file.
    - if more than one such bean exists, a fatal exception is thrown

4. constructor
    - similar to byType but type applies to constructor arguments.

5. autodetect
    - spring first tries to autowire by constructor, if it fails, spring tries to autowire by type.

Limitations of autowiring

- overriding possibility 
    dependencies can still be specified using <constructor-arg> and <property> setting which will override autowiring
- primitive datatypes
    we cannot autowire primitive datatypes
- less exact
    autowiring is less exact than explicit wiring

Sunday, August 23, 2020

Spring - The IoC Container

The Spring IoC Container creates the objects, wire them together, configure them and manage their complete lifecycle from creation till destruction.

There are two types of IoC containers:

1. Bean Factory Container
    - simplest container providing basic support for DI
    - proffered where resources are limited like mobile devices or applet based applications
    - e.g. XmlBeanFactory (this container reads the configuration metadata from an XML file)

2. Application Context Container
    - has more enterprise specific functionalities such as resolving textual messages from properties file and publishing application events to interested event listeners
    - e.g.
    - FileSystemXmlApplicationContext - load bean definition and configuration from an XML file. Need to provide full path of the xml file to the constructor.
    - ClassPathXmlApplicationContext - load bean definition and configuration from an XML file. The xml file should be present in the CLASSPATH
    - WebXmlApplicationContext - loads the XML file with definition of all beans from within a web application.

Spring Boot - Asynchronus Messaging (AMPQ)

Asynchronus messaging can reduce strain on the system
Spring uses RabbitMQ which is efficient for sending and receiving asynchronous messages.
Property based configuration
follows standard Rabbit consumption

Producer:
    Spring provides Rabbit Template
    Default configuration with spring boot
    Provide the exchange and queue name
    Allows to post messages as Object or String


Consumer:
    Spring provides listener implementations
    Response to messages in the queue and execute some logic

Spring - Boot - Data

Spring Data provides rich support for RDBMS and NoSQL databases.

Certain databases like H2/HSQLDB autoconfigure an embedded database

Leverage common scripts to prime embedded database





Saturday, August 22, 2020

Spring - Boot

Spring Boot 
    - supports rapid development
    - removes boilerplate of most of the application setup
 
Key components
    - Embedded Tomcat
    - Auto configuration of Application context
    - Automatic servlet mapping
    - Embedded database support and hibernate/JPA dialect
    - Automatic controller mapping

Spring - Aspects

Spring Aspects are blocks of code that can be injected into the application at runtime

example logging, transaction management, caching, security.


- Spring uses AspectJ (byte code modification - run time interweaving) for aspecting.


Parts of spring Aspect

- Aspect - a class that implements enterprise application concerns that cut across multiple classes.                         Aspects can be a normal class configured through Spring XML configuration or we can use                     Spring AspectJ integration to define a class as Aspect using @Aspect annotation.

- Join Point - the place or specific point in the application code flow where the aspect code will be applied

- Point Cut - a selection criteria to select the 'Join Point' to apply the aspect code.

- Advice - The advice is the aspect class method that will be applied at the 'Join Point' selected by the 'Point Cut'


Point Cut:

Syntax: designator("r p.c.m(arg)")

r- return type

p- package

c-class

m-method

arg-arguments

designator-there are several designators provided by spring which can be used to implement an aspect.

e.g. execution - for matching method execution

        within-for matching within certain types

        target-for matching a specific type

        @annotation-for matching a specific annotation



Wednesday, August 19, 2020

Spring Lifecycle

The three phases of lifecycle:

    1. Initialization

    - begins when the application context is created.

    - can be broken down in to further two phases

        a) BeanFactory Initialization

        b) Bean Initialization and Instantiation

    2. Use


    3. Destruction

    - begins when close is called on the application context.



Some examples of lifecycle methods:

@PostConstruct

a method which should be executed after construction of the object.


@PreDestroy

a method which should be called before marking the object for garbage collection.



Spring - Component Scanning

 Component scanning scans a base package and loads configuration automatically for each bean it finds. Component scanning occurs at the application startup. The base package can be defined in java or xml configuration.


@Component

@Component indicates that the class should be loaded in the BeanFactory. Tells spring to include this class in component scanning.

@Component is the root annotation and it have several stereotypes, like @Service


@Autowired

@Autowired indicates that class has a dependency on the bean, which is used by spring IoC to inject the dependency.


@Qualifier

@Qualifier is used when multiple implementation of an interface are needed


@Value

properties are injected with @Value annotation.



Spring Proxies

 In Spring, Everything is a Proxy.

Proxies are used by spring to add behaviour in the application classes.

All classes in spring get wrapped at-least in one proxy.

Spring uses both JSK and CGLib based proxies to achive the final spring behaviour.


Note:

private members / methods are not exposed by the proxies.

behavours added to the classes only impacted by calls thriugh the proxy.

Internal call to classes do not get the proxy behaviours.


Tuesday, August 18, 2020

Spring Bean Scope

 Spring Bean Scopes:

There are different types of Bean Scopes which spring provides.

The commonly used and default bean scope in spring is SINGLETON bean scope.

if no bean scope is specifically defined, spring uses sigleton bean scope. i.e. we get one instance per context of any bean.


Types of Bean Scope:

1. Sigleton Scope:

    We get to instantiate only once.

2. Prototype Scope:

    A new instance every time it is referenced. The instance is made available for garbage collection once it it no longer needed for reference.

This scope is useful for transient data or flex based application state

3. Session Scope:

    one instance of bean per user session.

    only available for web applications.

4. Request scope:

    one instance per request in the application

    only available for web applications.

    

Saturday, August 15, 2020

Spring Expression Language

 The Spring Expression language is a powerfull expression language for Spring Applications.

It Supports querying and manipulating object graph at runtime.


e.g.

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("new String('hello world').toUpperCase()");
String message = exp.getValue(String.class);


SpEL expressions can be used with XML or annotation-based configuration metadata for defining BeanDefinitions. In both cases the syntax to define the expression is of the form
  #{ <expression string> }.

Friday, August 14, 2020

Spring-Profiles

 Spring allows to create different profiles for an application - like Dev, Test, Prod

It is a way to segregate different application configurations and make it available only in certain environment.

Any @Component or @Configuration can be marked with @Profile to limit when it is loaded:

@Configuration
@Profile("production")
public class ProductionConfiguration {

    // ...

}

we can use spring.profiles.active to specify which profiles are active.

Thursday, August 13, 2020

Spring -Configuration (JavaConfig)

 There are many ways to configure a spring application. like XML based configuration.


JAVA Configuration is the most currently used spring configuration, because of various benefits it provides like-

- Native language syntax

- compile time checking of configuration.

- easier IDE integration.


Annotating a class with @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definition.

@Bean annotation tells spring that a method annotated with @Bean annotation should be registered as a bean in the application context.

e.g.

@Configuration
public class HelloWorldConfig {
   @Bean 
   public HelloWorld helloWorld(){
      return new HelloWorld();
   }
}


@Bean annotation tells the spring that the method will return an object that should be registered as a bean in Spring Application Context

Spring - Application Context

 Application Context acts as the heart of the SpringApplication.

The Application Context encapsulates the Bean Factory and provides access to bean factory under controlled situations.

Application Context provides the metadata for bean creation.

Application Context ensures that the beans are created in appropriate order.

There will always be at least one application context in a Spring Application


Multiple Application Context:

    A Spring application can have more than one Application context.

    In case of multiple application context, the parent context can interact with the children context(s) and not vice-versa.



Monday, August 10, 2020

Dependency Injection - DI

Dependency Injection is a pattern to implement IoC in which the control of injecting object dependencies is transferred to the framework.

Dependency injection can happen in the way of passing parameters to the constructor or by post-construction using setter methods.

In traditional programming:


public class Store {

    private Item item;

    public Store() {

        item = new ItemImpl1();    

    }

}



In the above example the 'Item' implementation is done in the store class itself.


In DI,


public class Store {

    private Item item;

    public Store(Item item) {

        this.item = item;

    }

}


Now, to provide the implementation of the 'Item' interface, we can follow various ways. The one below is constructor based dependency injection.


@Configuration

public class AppConfig {

    @Bean

    public Item item1() {

        return new ItemImpl1();

    }

    @Bean

    public Store store() {

        return new Store(item1());

    }

}


Types of dependency injection

1. constructor based

    when the constructor invokes a class with a number of arguments, each representing a dependency on other class

2. setter based

    calling setter methods on the beans after invoking a no-argument constructor. Use of @Required on a setter makes the setter a required dependency

we can also use a mixture of both constructor based and setter based dependency injection. The good option is to use constructor arguments for mandatory dependencies and setter for optional dependencies.


Benefits of dependency Injection

- minimizes the amount of code
- makes application easy to test
- loose coupling
- eager instantiation and lazy loading of services

Inversion of Control - IoC

Inversion of Control is one of the critical design pattern of Spring Framework.

In this application development pattern -

    the control of portions of program is transferred to a container or framework.

    unlike in traditional programming where custom code makes call to libraries or framework.


The advantages-

decoupling of execution from implementation.

greater modularity


Inversion of control can be achieved through various mechanism such as:

Strategy design pattern

Service Locator Pattern

Factory Pattern

Dependency Injection

 

Spring Introduction

Spring is a JAVA framework to provide the "Plumbing" for enterprise applications, So that teams can focus on business logic

Spring is the most popular application development framework.

Spring is Open Source

Key Features :

  • Core technologies: dependency injection, events, resources, i18n, validation, data binding, type conversion, SpEL, AOP.

  • Testing: mock objects, TestContext framework, Spring MVC Test, WebTestClient.

  • Data Access: transactions, DAO support, JDBC, ORM, Marshalling XML.






  • Different modules of spring framework:
    - Core Module
    - Bean Module
    - Context Module
    - Expression Language Module
    - JDBC Module
    - ORM Module
    - Web Module
    - JMS Module
    - Transaction Module

Spring - AutoWiring

Spring automatically resolves the dependencies between the collaborating beans by inspecting the contents of the BeanFactory. This is called...