Spring Framework

Spring Framework

What is Spring Framework?

Spring is one of the most popular frameworks for Java enterprise edition. Developers all over the world use spring for developing reliable and high-quality applications. Spring framework was designed by Rod Johnson. Since then spring has become alternative technology in java world for EJB model. You can create any application by using spring framework.

Spring Framework – DI, IOC, AOP

It is impossible to understand what Spring Framework is without understanding what Dependency Injection is, it is one of the types of Inversion of Control (IOC).

 Inversion of Control:

This is the principle of object-oriented programming, in which objects of the program do not depend on concrete implementations of other objects, but may have knowledge about their abstractions (interfaces) for later interaction.

Inversion of Control can be achieved through various mechanisms such as: (Strategy design pattern, Service Locator pattern, Factory pattern, and Dependency Injection (DI)).

Dependency Injection:

is a composition of structural design pattern, in which for each function of the application there is one, a conditionally independent object (service) that can have the need to use other objects (dependencies) known to it by interfaces. Dependencies are transferred (implemented) to the service at the time of its creation. This is a situation where we introduce an element of one class into another. In practice, DI is implemented by passing parameters to the constructor or using setters. Libraries that implement this approach are also called IOC containers.

public class School {

    private Class class;

  

    public Store() {

        class = new ClassImpl1();   

    }

}

 

 

In the example above, we need to instantiate an implementation of the Class interface within the School class itself.

By using DI, we can rewrite the example without specifying the implementation of Class that we want:

public class School {

    private Class class;

    public School (Class class) {

        this.class = class;

    }

}

 

Aspect oriented programming:

A programming paradigm that allows you to distinguish cross-through (functional) functionality in application. These functions, which span multiple application nodes, are called cross-cutting concerns and these cross-cutting notes are separated from the immediate business logic of the application.

In OOP, the key unit is the class, while in AOP, the key element is the aspect. DI helps to separate application classes into separate modules, and AOP helps to separate cross-cutting concerns from the objects they affect.

Spring Framework Architecture:

Spring Framework is divided into a number of separate modules, which allows you to decide which ones to use in your application. Below image illustrates the most important modules of Spring Framework architecture.

Spring Framework Core Components

The Core container from spring consists of four modules: SpEL, Context, Core, Beans. Description for these elements are as follows:

1.     The SpEL module provides a powerful expression language for manipulating objects during execution.

2.     Context is built on the basis of Beans and Core and allows you to access any object that is defined in the settings. The key element of the Context module is the Application Context interface.

3.     The Core module provides key parts of the framework including IOC and DI properties.

4.     The Bean module is responsible for creating and managing Spring Beans – is application context structure unit.

Spring Framework Web

Spring framework Web layer consists of Web, Web-MVC, Web-Socket, Web-Portlet etc.

1.     The Web module provides functions such as downloading files, creating web application, rest web service etc.

2.     Web-MVC contains a Spring MVC implementation for web applications.

3.     Web-Socket provides support for communication between the client and the server, using Web-Sockets in web applications.

4.     Web-Portlet provides MVC implementation with portlet environment

Spring Framework Data Access

The Data Access/Integration container consists of JDBC, ORM, OXM, JMS and the Transactions module.

1.     JDBC provides an abstract layer of JDBC and eliminates the need for the developer to manually register the monotonous code associated with connecting to the database.

2.     Spring ORM provides integration with such popular ORMs as Hibernate, JDO, JPA, etc.

3.     The OXM module is responsible for linking the Object / XML – XMLBeans, JAXB, etc.

4.     The JMS (Java Messaging Service) module is responsible for creating, sending and receiving messages.

5.     Transactions supports transaction management for classes that implement certain methods and POJOs.

The Spring IOC Container:

An IOC container is a common characteristic of frameworks that implement IOC.

In the spring framework, the IOC container is represented by the interface ApplicationContext. The Spring container is responsible for instantiating, configuring and assembling objects known as beans, as well as managing their lifecycle.

The spring framework provides several implementations of the ApplicationContext interface — ClassPathXmlApplicationContext and FileSystemXmlApplicationContext for standalone applications, and WebApplicationContext for web applications.

In order to assemble beans, the container uses configuration metadata, which can be in the form of XML configuration or annotations.

Here’s one way to manually instantiate a container:

 

ApplicationContext context

  = new ClassPathXmlApplicationContext ("applicationContext.xml");

 

Dependency Injection in spring

To set the class attribute in the example above, we can use metadata. Then, the container will read this metadata and use it to assemble beans at runtime.

Dependency Injection in spring can be done through constructors, setters or fields.

Constructor-Based Dependency Injection

In the case of constructor-based dependency injection, the container will invoke a constructor with arguments each representing a dependency we want to set.

Spring resolves each argument primarily by type, followed by name of the attribute and index for disambiguation. Let’s see the configuration of a bean and its dependencies using annotations:

@Configuration

public class AppConfig {

    @Bean

    public Class class1() {

        return new ClassImpl1();

    }

    @Bean

    public School school() {

        return new School(class1());

    }

}

The @Configuration annotation indicates that the class is a source of bean definitions. Also, we can add it to multiple configuration classes.

The @Bean annotation is used on a method to define a bean. If we don’t specify a custom name, the bean name will default to the method name.

For a bean with the default singleton scope, spring first checks if a cached instance of the bean already exists and only creates a new one if it doesn’t. If we’re using the prototype scope, the container returns a new bean instance for each method call.

Another way to create the configuration of the beans is through XML configuration:

<bean id="class1" class="com.myapp.school.ClassImpl1" />

<bean id="school" class="com.myapp.school.School">

    <constructor-arg type="ItemImpl1" index="0" name="item" ref="item1" />

</bean>

Field-Based Dependency Injection

In case of Field-Based DI, we can inject the dependencies by marking them with a @Autowired annotation:

public class School {

    @Autowired

    private Class class;

}

While constructing the School object, if there’s no constructor or setter method to inject the Class bean, the container will use reflection to inject Class into School.

We can also achieve this using XML configuration.

This approach might look simpler and cleaner but is not recommended to use because it has a few drawbacks such as:

  • This method uses reflection to inject the dependencies, which is costlier than constructor-based or setter-based injection
  • It’s really easy to keep adding multiple dependencies using this approach. If you were using constructor injection having multiple arguments would have made us think that the class does more than one thing which can violate the Single Responsibility Principle.

Advantages of Spring Framework

-       It utilizes some of the well-known technologies, ORM frameworks, logging frameworks, JEE, JDK timers, Quartz and so on. So, developers don’t have to learn any new technologies or frameworks.

-       DI: It is easy to test the spring application the main reason behind this is because environment dependent code available in this framework. Also, dependency injection simplifies injecting the test data with the help of the JavaBean-style POJOs.

-       IoC: Spring framework provides inversion of control and APIs to translate technology-driven exceptions, specifically thrown by JDBC, Hibernate.

-       Modularity: spring makes it easy for the developers to know which packages or classes are to be used and which one should be ignored. No matter how many number of packages and classes are there, it is easy for the developers to identify and utilize the usable ones.

-       Spring AOP also brings many of benefits: There is no need for a developer to have a separate compilation unit or a separate class loader. Also, it uses IOC for dependency injection, which means aspects can be configured normally.

-       Spring Framework vs EJB

Spring empowers POJO programming: It enables developers to build enterprise-level applications with the help of the POJOs. The POJO helps you get rid of conventional EJB container products by letting you use a robust servlet container like Tomcat.

Note: POJO means Plain Old Java Object. It refers to a Java object (instance of definition) that isn't bogged down by framework extensions. For example, to receive messages from JMS, you need to write a class that implements the MessageListener interface.

Disadvantages of the Spring Framework

-       Longer learning curve : if you newbie developer , it would be difficult to learn spring framework The main reason behind this is a whole host of new programming methods and detailing require understanding how to set up the Spring XML configuration file.

-       All the spring applications require a lot of XML: If you’ve ever worked with spring framework, you might be knowing that applications developed using spring framework often require a huge amount of XML. So, if you’re considering spring for your next development, be prepared to spare a lot of time coding in XML.

Conclusion

In this article I have introduced with the spring framework, its architecture and main features. We have learned how the spring framework helps us develop loosely coupled applications using dependency injection where the dependent objects are injected using a configuration file.

 

要查看或添加评论,请登录

Ahmed Hassan的更多文章

  • My Registration and Login Demo

    My Registration and Login Demo

    https://github.com/saqrmasr/Spring-Boot-Rest-MYSQL-Login-Registration.

  • Spring Boot

    Spring Boot

    What is Spring Boot? - Spring Boot is a Framework from “The Spring Team” to ease the bootstrapping and development of…

社区洞察

其他会员也浏览了