top of page
Writer's pictureJay Joshi

Spring Framework with its basic Annotations

Spring Framework

·       Spring is a powerful open source, application framework created to reduce the complexity of enterprise application development.

·       It is light-weighted and loosely coupled.

·       It has layered architecture, which allows you to select the components to use, while also providing a cohesive framework for J2EE application development.

·       Spring framework is also called the framework of frameworks as it provides support to various other frameworks such as Hibernate, EJB, etc.

Inversion of Control (IoC) and Dependency Injection

The objects give their dependencies instead of creating or looking for dependent objects is called Inversion of Control.

IoC is also known as dependency injection (DI). It is a process whereby objects define their dependencies, with the other objects they work, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method.

The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse, hence the name Inversion of Control (IoC), meaning that the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern.


IoC Container

At the core of the Spring Framework, lies the Spring container. The container creates the object, wires them together, configures them and manages their complete life cycle. The Spring container makes use of Dependency Injection to manage the components that make up an application. The container receives instructions for - which objects to instantiate, configure, and assemble by reading the configuration metadata provided. This metadata can be provided either by XML, Java annotations or Java code.


Dependency Injection

In Dependency Injection, you do not have to create your objects but have to describe how they should be created. You don’t connect your components and services together in the code directly, but describe which services are needed by which components in the configuration file. The IoC container will wire them up together.


Two types of IoC containers

  1. BeanFactory (Interface)

The BeanFactory interface provides an advanced configuration mechanism capable of managing any type of object.

In short, the BeanFactory provides the configuration framework and basic functionality.

  1. ApplicationContext (Sub-interface of BeanFactory)

It adds easier integration with Spring's AOP features; message resource handling (for use in internationalization), event publication; and application-layer specific contexts such as the WebApplicationContext for use in web applications.

The ApplicationContext adds more enterprise-specific functionality.


The interface org.springframework.context.ApplicationContext represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the aforementioned beans.


The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata. The configuration metadata is represented in XML, Java annotations, or Java code. It allows you to express the objects that compose your application and the rich interdependencies between such objects.

 

Advantages of Spring Framework

  • Because of Spring Frameworks layered architecture, you can use what you need and leave which you don’t.

  • Spring Framework enables POJO (Plain Old Java Object) Programming which in turn enables continuous integration and testability.

  • JDBC is simplified due to Dependency Injection and Inversion of Control.

  • It is open-source and has no vendor lock-in.

 

Different features of Spring Framework

  • Lightweight: Spring is lightweight when it comes to size and transparency. 

  • Inversion of control (IOC): The objects give their dependencies instead of creating or looking for dependent objects. This is called Inversion of Control.

  • Aspect oriented Programming (AOP): Aspect oriented programming in Spring supports cohesive development by separating application business logic from system services.

  • Container: Spring Framework creates and manages the life cycle and configuration of the application objects.

  • MVC Framework: Spring Framework’s MVC web application framework is highly configurable. Other frameworks can also be used easily instead of Spring MVC Framework.

  • Transaction Management: Generic abstraction layer for transaction management is provided by the Spring Framework. Spring’s transaction support can be also used in container less environments.

  • JDBC Exception Handling: The JDBC abstraction layer of the Spring offers an exception hierarchy, which simplifies the error handling strategy.

Modules in Spring Framework

 

Spring configuration file

A Spring configuration file is an XML file. This file mainly contains the classes information. It describes how those classes are configured as well as introduced to each other. The XML configuration files, however, are verbose and cleaner. If it’s not planned and written correctly, it becomes very difficult to manage in big projects.


Components of a Spring application

  • Interface: It defines the functions.

  • Bean class: It contains properties, its setter and getter methods, functions etc.

  • Spring Aspect Oriented Programming (AOP): Provides the functionality of cross-cutting concerns.

  • Bean Configuration File: Contains the information of classes and how to configure them.

  • User program: It uses the function.

 

Some of the benefits of IoC.

  • It will minimize the amount of code in your application.

  • It will make your application easy to test because it doesn’t require any singletons or any lookup mechanisms in your unit test cases.

  • It promotes loose coupling with minimal effort and least intrusive mechanism.

  • It supports eager instantiation and lazy loading of the services.

 

What do you understand by auto wiring and name the different modes of it?

The Spring container is able to autowire relationships between the collaborating beans. That is, it is possible to let Spring resolve collaborators for your bean automatically by inspecting the contents of the BeanFactory.Different modes of bean auto-wiring are:

  1. no: This is default setting which means no autowiring. Explicit bean reference should be used for wiring.

  2. byName: It injects the object dependency according to name of the bean. It matches and wires its properties with the beans defined by the same names in the XML file.

  3. byType: It injects the object dependency according to type. It matches and wires a property if its type matches with exactly one of the bean’s names in XML file.

  4. constructor: It injects the dependency by calling the constructor of the class. It has a large number of parameters.

  5. autodetect: First the container tries to wire using autowire by constructor, if it can’t then it tries to autowire by byType.

Limitations with auto wiring

Following are some of the limitations you might face with auto wiring:

  • Overriding possibility: You can always specify dependencies using <constructor-arg> and <property> settings which will override autowiring.

  • Primitive data type: Simple properties such as primitives, Strings and Classes can’t be autowired.

  • Confusing nature: Always prefer using explicit wiring because autowiring is less precise.

Annotation-based container configuration

Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration. It acts as an alternative to XML setups.

Difference between @Component, @Controller, @Repository & @Service annotations in Spring?

@Component: This marks a java class as a bean. It is a generic stereotype for any Spring-managed component. The component-scanning mechanism of spring now can pick it up and pull it into the application context.

@Controller: This marks a class as a Spring Web MVC controller. Beans marked with it are automatically imported into the Dependency Injection container.

@Service: This annotation is a specialization of the component annotation. It doesn’t provide any additional behavior over the @Component annotation. You can use @Service over @Component in service-layer classes as it specifies intent in a better way.

@Repository: This annotation is a specialization of the @Component annotation with similar use and functionality. It provides additional benefits specifically for DAOs. It imports the DAOs into the DI container and makes the unchecked exceptions eligible for translation into Spring DataAccessException.

What do you understand by @Required annotation?

@Required is applied to bean property setter methods. This annotation simply indicates that the affected bean property must be populated at the configuration time with the help of an explicit property value in a bean definition or with autowiring. If the affected bean property has not been populated, the container will throw BeanInitializationException.

What do you understand by @Autowired annotation?

The @Autowired annotation provides more accurate control over where and how autowiring should be done. This annotation is used to autowire bean on the setter methods, constructor, a property or methods with arbitrary names or multiple arguments. By default, it is a type driven injection.

What do you understand by @Qualifier annotation?

When you create more than one bean of the same type and want to wire only one of them with a property, you can use the @Qualifier annotation along with @Autowired to remove the ambiguity by specifying which exact bean should be wired.


For example, here we have two classes, Employee and EmpAccount respectively. In EmpAccount, using @Qualifier its specified that bean with id emp1 must be wired.

 

What do you understand by @RequestMapping annotation?

@RequestMapping annotation is used for mapping a particular HTTP request method to a specific class/ method in controller that will be handling the respective request. This annotation can be applied at both levels:

  • Class level: Maps the URL of the request

  • Method level: Maps the URL as well as HTTP request method

 

Which classes are present in spring JDBC API?

Classes present in JDBC API are as follows:

  1. JdbcTemplate

  2. SimpleJdbcTemplate

  3. NamedParameterJdbcTemplate

  4. SimpleJdbcInsert

  5. SimpleJdbcCall


Spring Profiling

 

Spring Profiles provides a powerful and easy way to control code and configuration based on the environment.

Using Spring Profiles it’s possible to segregate parts of our application and make it only available in certain environments.

We can use @Profile annotation to limit the availability of any @Component or @Configuration.

Profiles are a core feature of the framework — allowing us to map our beans to different profiles — for example, dev, test, and prod.

We can then activate different profiles in different environments to bootstrap only the beans we need.

 

1.     Use @Profile Annotation

@Service
@Profile("development")
public class DevDBConnection implements  DatabaseService {
    
    @Override
    public void getDBConnection() {
        System.out.println("DEV DB connection established");
    }
}

 

2.     Using Command Line

We can pass profile information to Spring Boot using the switch through command prompt —spring.profiles.active=development,staging

 

3.  Using Property File

We can use standard Spring environment property spring.profiles.active property in our application.properties or application.yml to specify active profiles.

spring.profiles.active=development,staging

 

Programmatically setting profile

We can programmatically set active profile by calling setAdditionalProfiles(...) method provided by SpringApplication class

SpringApplication app = new SpringApplication(Application.class);
app.setAdditionalProfiles("development","production");

 

Development Profile

@Profile("development")

 

Production Profile

@Profile("production")

 

Staging Profile

@Profile("staging")

12 views0 comments

Recent Posts

See All

Battle of the Backends: Java vs Node.js

Comparing Java and Node.js involves contrasting two distinct platforms commonly used in backend development. Here’s a breakdown of their...

Comments


bottom of page