Advantages of Spring

Dependency Injection 

All the dependency initialization code will be moved out of the Class. Only functionality remains inside the class. Classes become More readable, Loosely Coupled.

Main class in this example is dependent on a dependency object. But, it does not bother to initialize it. Because spring takes care of this aspect.


Public class Main{

  private Dependency dependency;

  @Autowired
  public Main(Dependency dependency){

     this.dependency= dependency

  }

  public static void main(String []args){

    ApplicationContext context = SpringApplication.run(Main.class, args);

    Dependency dependency = (MyAppConfig) context.getBean("dependency");

    System.out.println(dependency.toString());

  }

}


Public class Dependency{

  private String name;

  public Dependency(String name){
     this.name = name;
 } 

  public void run(){
    System.out.println("Name:"+name);
  }
}

Dependencies can be injected through XML or Code

XML:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="dependency" class="com.spring.domain.Dependency">
        <constructor-arg index="0" ref="JAVA"/>

    </bean>
</beans>


JAVA

@Configuration
@ComponentScan("com.spring")
public class Config {

    @Bean
    public Dependency dependency() {
        return new Dependency("JAVA");
    }
}


Light weighted 

Every spring module is bundled as a different jar (eg: MVC, Data, Boot, Context(Default), etc). we can add only the required jars for our work and ignore the rest.


Unified interfaces

Spring provides a common interface for a variety of technologies that are available in the market. 

Examples:
  1.  Spring Data API(interface) is same for different ORM vendors like Hibernate &  IBATIS.
  2.  Spring Cloud API is same for different cloud providers

Comments

Popular posts from this blog

Distributed database design using CAP theorem

SQL Analytical Functions - Partition by (to split resultset into groups)

Easy approach to work with files in Java - Java NIO(New input output)