KEMBAR78
Spring Config - Core | PDF | Class (Computer Programming) | Java (Programming Language)
0% found this document useful (0 votes)
53 views14 pages

Spring Config - Core

Spring Configuration is a framework setup for Java applications that allows customization of application behavior through three types: XML, Annotation-based, and Java-based configurations. It manages objects (beans) and their dependencies via Dependency Injection (DI), promoting modularity and reducing tight coupling. The document outlines the advantages of using beans, including lifecycle management, configuration flexibility, and support for Aspect-Oriented Programming (AOP).

Uploaded by

deeep
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views14 pages

Spring Config - Core

Spring Configuration is a framework setup for Java applications that allows customization of application behavior through three types: XML, Annotation-based, and Java-based configurations. It manages objects (beans) and their dependencies via Dependency Injection (DI), promoting modularity and reducing tight coupling. The document outlines the advantages of using beans, including lifecycle management, configuration flexibility, and support for Aspect-Oriented Programming (AOP).

Uploaded by

deeep
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Spring Configuration

What is Spring Configuration?

Spring is a framework used to build Java applications, and configuration in Spring is a way to
set up and customize how your application behaves. It's essentially telling Spring how you
want your application to work and how it should manage things like your objects (beans),
databases, etc.

There are three types of configuration in Spring:


1. XML Configuration
2. Annotation-based Configuration
3. Java-based Configuration (Java Config)

Why are we using configuration in Spring?

Configuration in Spring is needed to set up the beans (objects or components) that Spring
manages for you. It helps Spring understand how to create, wire, and manage these beans so
that your application runs as expected. Instead of manually creating and managing objects
yourself, Spring does it for you in a more organized way.

Why Do We Use Beans in Spring?

In Spring Framework, a bean is an object that is managed by the Spring IoC (Inversion of
Control) container. These beans form the backbone of a Spring application, as they are the
objects that Spring instantiates, configures, and manages. Using beans has several
advantages, and understanding why they are needed helps grasp the fundamentals of Spring.

Key Reasons for Using Beans in Spring

1. Centralized Object Management

• Without Spring: You manually create and manage objects in your application code.
• With Spring Beans: Spring takes responsibility for creating and managing the
lifecycle of objects, simplifying development.
• Benefit: Centralized management allows consistent behavior and efficient resource
handling.

Example Without Spring:

java

GreetingService greetingService = new GreetingService();


With Spring:

java

@Component
public class GreetingService { }
// Spring container creates and manages the GreetingService bean.

2. Dependency Injection (DI)

• Beans enable Spring to perform DI, which is a design pattern where dependencies are
provided to an object instead of the object creating them itself.
• Benefit: This reduces tight coupling between objects and promotes a modular,
maintainable, and testable application design.

Example:

java

@Component
public class Person {
@Autowired
private GreetingService greetingService; // Dependency injected by
Spring
}

3. Lifecycle Management

• Spring beans have a lifecycle: creation, initialization, and destruction.


• You can define custom initialization and destruction logic using:
o XML configuration: <init-method> and <destroy-method>.
o Annotations: @PostConstruct and @PreDestroy.
• Benefit: You can control how beans are created, initialized, and destroyed.

4. Singleton and Other Scopes

• Beans in Spring can be created with different scopes, such as:


o Singleton (default): Only one instance of the bean is created and shared.
o Prototype: A new instance is created each time the bean is requested.
o Other scopes like request, session, etc., for web applications.
• Benefit: Scope flexibility ensures optimal resource usage.

Example (Singleton):

java

@Component
public class GreetingService {
// Singleton: Shared across the application.
}

5. Loose Coupling

• Beans reduce tight coupling between components by relying on interfaces and DI


rather than directly instantiating objects.
• Benefit: Loose coupling ensures easier modifications, testing, and scaling of
applications.

Example of Tight Coupling:

java

public class Person {


private GreetingService greetingService = new GreetingService();
}

Loose Coupling with Beans:

java

@Component
public class Person {
@Autowired
private GreetingService greetingService;
}

6. Configuration Flexibility

• Beans can be defined in multiple ways:


o XML-based Configuration
o Annotation-based Configuration
o Java-based Configuration
• Benefit: You can choose the configuration style that suits your project or team
preferences.

7. AOP (Aspect-Oriented Programming) Support

• Beans in Spring can be enhanced using AOP to add cross-cutting concerns like
logging, security, or transaction management without modifying the core logic.
• Benefit: Keeps business logic clean and separates concerns effectively.
1. Using XML for Dependency Injection

Concept:

• In XML configuration, you define the beans and their dependencies in an XML file. Spring
reads this file and knows how to inject dependencies.

Example: XML Configuration for DI

Imagine we have two classes:

GreetingService:

Person:
Here:

• The Person class depends on GreetingService.


• Instead of creating the GreetingService object manually in Person, we’ll use Spring to
inject it.

XML Configuration:

The XML file (applicationContext.xml) defines the beans and their relationships:

Explanation of XML:

1. The <bean> tag defines a bean (an object managed by Spring).


o The id is the bean name.
o The class is the fully qualified class name of the object to create.
2. The <property> tag specifies which property of the class to inject, using the name attribute
(matches the setter method name).
3. The ref attribute specifies the bean to inject (greetingService).

Main Method to Test:


Output:
Hello, John!

How Dependency Injection Happens in XML:

1. Spring reads the applicationContext.xml file.


2. It creates the GreetingService bean.
3. It creates the Person bean and injects the GreetingService bean into it using the setter
method (setGreetingService()).
4. When you call person.greet(), the Person object already has the GreetingService
injected.

2. Using Annotations for Dependency Injection

Concept:

• In annotation-based configuration, you use annotations like @Component, @Autowired, and


@Configuration in your Java classes.
• This approach eliminates the need for XML files.

1. @Component

• What it does: It tells Spring, "This class is something you need to manage (create an
object for it and handle it)."
• Where we use it: On classes that should be treated as beans by Spring.
• Why we use it: To make the class available for dependency injection.

Example:

java
@Component
public class GreetingService {
public String sayHello() {
return "Hello!";
}
}

2. @Autowired

• What it does: It tells Spring, "Put the object I need here automatically."
• Where we use it: On fields, constructors, or setter methods.
• Why we use it: To connect one bean to another without writing new Object()
manually.

Example (Field Injection):

java

@Component
public class Person {

@Autowired
private GreetingService greetingService; // Spring puts the
GreetingService object here.

public void greet() {


System.out.println(greetingService.sayHello());
}
}

3. @Configuration

• What it does: It tells Spring, "This class has the instructions to create beans
(objects)."
• Where we use it: On a class that provides methods to define beans.
• Why we use it: To replace XML configuration with Java code.

Example:

java

@Configuration
public class AppConfig {
@Bean
public GreetingService greetingService() {
return new GreetingService(); // This method tells Spring how to
create a GreetingService object.
}
}

4. @Bean
• What it does: It tells Spring, "This method provides the object you need to manage."
• Where we use it: Inside a @Configuration class.
• Why we use it: To manually define a bean when annotations like @Component are not
used.

Example:

Java

@Bean
public Person person(GreetingService greetingService) {
return new Person(greetingService); // Spring will call this method and
use its result as a bean.
}

5. @Qualifier

• What it does: It tells Spring, "Use this specific bean when there are multiple options."
• Where we use it: On fields, constructors, or setter methods.
• Why we use it: To choose between beans with the same type.

Example:

java

@Component("morningService")
public class MorningGreetingService implements GreetingService { }

@Component("eveningService")
public class EveningGreetingService implements GreetingService { }

@Component
public class Person {
@Autowired
@Qualifier("morningService")
private GreetingService greetingService;
}

Example: Annotation Configuration for DI

The same GreetingService and Person classes, but now using annotations.

GreetingService:
Person:

Configuration Class:

We don’t need an XML file. Instead, we use a Java class to configure Spring:
Main Method to Test:

Output:
Hello, John!

How Dependency Injection Happens with Annotations:

1. Spring scans the com.example package for classes annotated with @Component.
2. It finds GreetingService and Person and creates beans for them.
3. The @Autowired annotation on the setGreetingService() method tells Spring to inject
the GreetingService bean into the Person bean.
4. When you call person.greet(), the Person object already has the GreetingService
injected.

3. Java-based Configuration (Java Config)


This is a variant of annotation-based configuration. Instead of using annotations like
@ComponentScan, you write Java code in a class and define methods that return beans.
You’re still writing Java code, but now Spring can manage your beans and dependencies for
you.

Step 1: Modify the Person Class to Have a Dependency

Let's introduce a GreetingService that will handle greeting logic.

Here, the Person class now depends on GreetingService to provide the greeting logic. We
pass the GreetingService through the constructor to inject the dependency.

Step 2: Create the GreetingService Class

Now, let’s create a simple GreetingService class.

Step 3: Modify the AppConfig Class to Configure the Dependencies


We need to modify the Spring configuration class (AppConfig) to tell Spring how to inject
the GreetingService into the Person object.

Now, Spring will:

1. Create a GreetingService bean because of the @Bean method


greetingService().

2. Inject the GreetingService bean into the Person constructor. This is Dependency
Injection—Spring automatically provides the required GreetingService object
when creating the Person bean.

Step 4: Modify the MainApp Class

The MainApp class doesn't need to change; it will still retrieve the Person bean from the
Spring context and call the greet() method.
Where is Dependency Injection Happening?

Let’s go step by step with debugging to understand exactly where Dependency Injection
happens:

1. Creating AnnotationConfigApplicationContext:
o Spring reads the configuration from AppConfig.class.
o Spring finds the @Bean methods: greetingService() and person().
2. Creating GreetingService Bean:
o Spring calls the greetingService() method and creates an instance of
GreetingService.
3. Creating Person Bean with Dependency Injection:
o Spring calls the person() method.
o Spring sees that Person has a constructor that requires a GreetingService
instance.
o This is where Dependency Injection happens: Spring already knows how to
create the GreetingService bean (from step 2), so it injects the
GreetingService into the Person constructor.
4. Person Bean is Fully Constructed:
o Spring creates the Person object with the name "John" and the
GreetingService object that was injected.
5. Using the greet() Method:
o When you call person.greet(), Spring has already injected the
GreetingService into Person. The greet() method uses this service to
generate a greeting.

Output

The output will now be:

Hello, John!
Recap of Dependency Injection in the Example

• GreetingService is injected into Person via the constructor.


• Spring is responsible for creating and injecting the GreetingService bean into
the Person bean. This is done automatically by Spring, and you don’t need to
manually create or pass the GreetingService when creating a Person.

Summary

• Dependency Injection is the process where Spring injects the required dependencies
(like GreetingService) into a class (like Person).
• In this case, the Person class depends on the GreetingService, and Spring injects
it when creating the Person bean.
• The key part where DI happens is when Spring calls the person() method in
AppConfig and injects the GreetingService into the Person constructor.

Comparison Table

Annotation-based Java-based
Feature XML Configuration
Configuration Configuration
Uses annotations like
Uses XML files to define Uses Java classes and
Setup @Component and
beans and dependencies. @Bean methods.
@Autowired.
Verbose and harder to Cleaner, less boilerplate Cleaner, with full
Ease of Use
read. than XML. control using Java.
Good for externalized Tightly coupled to Java Fully Java-based and
Flexibility
configuration. code. flexible.
XML is harder to Code is easier to read and Highly readable and
Readability
maintain in large projects. understand. maintainable.
Requires XML parsers Requires annotations in Requires no external
Dependencies
and files. the source code. files, only Java.
Useful for legacy or Good for new, annotation- Best for modern, pure
Use Case
external configurations. friendly projects. Java projects.

You might also like