0% found this document useful (0 votes)
3 views59 pages

WT_UNIT4

The document provides an overview of the Spring Framework, highlighting its core components, advantages, and concepts such as Dependency Injection (DI) and Inversion of Control (IoC). It explains the modular architecture of Spring, the benefits of using POJOs, and the role of Aspect-Oriented Programming (AOP) in managing cross-cutting concerns. Additionally, it discusses bean scopes, particularly the singleton scope, and includes examples of creating and using beans within the Spring context.

Uploaded by

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

WT_UNIT4

The document provides an overview of the Spring Framework, highlighting its core components, advantages, and concepts such as Dependency Injection (DI) and Inversion of Control (IoC). It explains the modular architecture of Spring, the benefits of using POJOs, and the role of Aspect-Oriented Programming (AOP) in managing cross-cutting concerns. Additionally, it discusses bean scopes, particularly the singleton scope, and includes examples of creating and using beans within the Spring context.

Uploaded by

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

WEB TECHNOLOGY(KCA- Presented By:

Tarun Kumar
021) Sharma
WEB TECHNOLOGY(KCA-
021)

UNIT-4
(Spring)
SPRING CORE BASICS
 Spring Core Basic:

- Spring is the most popular application development framework


for enterprise Java. Developers use the Spring Framework to create
high performing, easily testable and reusable code.

- Spring framework is an open source for Java platform.

- Spring framework targets promotes good programming practices


by enabling a POJO model.
SPRING CORE BASICS
 Remarks:

 Spring is a dependency injection framework to make the java application


loosely coupled.

 Spring Framework makes the Java2E development very easy.

 Spring Framework was developed by Rod Johnson in June 2003 for


the first released of Apache 2.0.
SPRING FRAMEWORK
SPRING FRAMEWORK
 Spring Core in Spring Framework contains 4 modules:
Core
Bean
Context(J2E, JMS etc)
SPEL(Spring Exp. Language)
 Middle Layer contains 4 modules:
AOP
Aspect
Instrumentation
Messaging
Upper Layer contains 2 modules:
Web Integration
Data Access
ADVANTAGE OF SPRING
Easy Testing : Testing applications is simplified because environment-
dependent code is managed by the Spring framework. Use of JavaBean-style
POJOs makes it easier to inject test data through dependency injection.
Well-Designed Web MVC Framework : Spring's web framework offers a
robust and clean MVC architecture. It serves as a strong alternative to other
frameworks like Struts etc.
Consistent Exception Handling : Spring provides a unified API to convert
technology-specific exceptions (e.g., from JDBC, Hibernate, JDO) into consistent,
unchecked exceptions.
Lightweight IoC Container : Spring’s Inversion of Control (IoC) container is
lightweight compared to heavy EJB containers. Suitable for development and
deployment on machines with limited memory and CPU resources.
ADVANTAGE OF SPRING
POJO-Based Development: Spring enables development using Plain Old Java
Objects (POJOs), simplifying application design and reducing dependency on
complex frameworks.
No Need for EJB Container: Enterprise-class applications can be developed
without requiring an Enterprise JavaBeans (EJB) container or application server
i.e. A simple servlet container like Apache Tomcat is sufficient for deployment.
Modular Architecture: Spring is organized into well-defined modules.
Developers can use only the required modules and ignore the rest for the
application development.
Integration with Existing Technologies: This modular and integration-
friendly nature makes Spring a powerful and flexible framework for Java
enterprise development. by integrating with popular technologies such as: ORM
frameworks (e.g., Hibernate, JPA)|| Logging frameworks (e.g., Log4j, SLF4J)||Java
EE components (e.g., JDBC, JMS)||Task scheduling (e.g., Quartz, JDK timers)||View
DEPENDENCY INJECTION
 Java Application depends on multiple classes. In other word, Java
application contains multiple classes, where some classes depends
on another classes.

It means that one class is unable to perform its task without the
support other class. This concept is known as dependency, where
one class needs the object of other class. This object is created
manually by the programmer with the help of new keyword, where
as spring framework inject the required object at runtime with the
DEPENDENCY INJECTION
CONCEPTS
Dependency Injection (DI) : it is a design pattern used to remove
hard-coded dependencies and make the code loosely coupled,
maintainable and testable.

Dependency: When one class depends on another class (or


service).

Injection: Supplying the dependent object (dependency) from


outside the class rather than creating it inside.

In the Spring Framework, this is managed by the IoC (Inversion of


SPRING INVERSION OF
CONTROL (IOC)
Inversion of Control (IoC) is a core principle of the Spring
Framework. It refers to the process by which the control of object
creation and dependency management is transferred from the
application code to the Spring container.
Instead of objects creating or looking up their dependencies
directly, they declare what they need — typically through:
 Constructor arguments
 Factory method parameters, or
 Setter methods (properties)

The Spring IoC container then injects these dependencies when the
object is created or initialized. This approach promotes loose
coupling and enhances the testability, flexibility, and
maintainability of the application.
SPRING INVERSION OF
CONTROL (IOC)
Instead of a bean creating or locating its own dependencies (e.g.,
by directly instantiating other classes), the control is inverted. In
this model, the container is responsible for supplying the
dependencies to the bean at the time of its creation.

This approach is known as Inversion of Control (IoC), and when


the container provides the required dependencies, it is specifically
referred to as Dependency Injection.
SPRING INVERSION OF
CONTROL (IOC)
In Spring, the container determines which objects to create,
configure, and link together by using configuration metadata. This
metadata can be defined in various formats—such as XML files,
Java annotations or Java-based configuration classes.

The Spring IoC (Inversion of Control) container


leverages(control) simple Java POJO classes along with the
configuration metadata to assemble a fully initialized, functional
application.
SPRING INVERSION OF
CONTROL (IOC)
In Spring, there are two main types of IoC
(Inversion of Control) containers:
BeanFactory – Lightweight container, used in simple
or resource-constrained environments.
ApplicationContext – Full-featured container,
typically preferred for enterprise-level applications.
The ApplicationContext container includes all
functionality of the BeanFactorycontainer, so it is
generally recommended over BeanFactory.
BeanFactory can still be used for lightweight
applications like mobile devices or applet-based
applications where data volume and speed is
significant.
ASPECT ORIENTED
PROGRAMMING (AOP)
One important part of the Spring Framework is Aspect-Oriented
Programming (AOP). AOP is a way to divide a program into
different parts, especially for tasks that are used in many places
across the application.
Some features like logging, security, transactions, or caching
are used in many parts of a program. These are called cross-cutting
concerns because they affect many parts of the program, not just
one specific part.
Instead of writing the same code again and again, AOP lets you
write this kind of code once in a separate unit called an Aspect,
and then apply it wherever needed. This keeps your main business
logic clean and easier to manage.
ASPECT ORIENTED
PROGRAMMING (AOP)
In Object-Oriented Programming (OOP), classes are the main building
blocks. But in Aspect-Oriented Programming (AOP), the main building
blocks are called aspects.
Dependency Injection (DI) helps you keep your code flexible(decouple
your application) by connecting different parts of your program without
needs to know about each other.
AOP helps you keep your code clean by separating common tasks (like
logging, security checks, etc.) that are needed in many places in your
code. These tasks are called cross-cutting concerns.
You can think of AOP like triggers in some programming languages —
extra actions that happen automatically when something happens.
Spring's AOP module lets you run extra code before or after a method
runs. For example, you can log a message every time a method is called
without changing the actual method code.
AOP CONCEPTS AND
TERMINOLOGY
Aspect:
Think of an aspect like a helper tool that handles common tasks
used in many places. For example, managing database
transactions (start, commit, rollback) is something you need in
different parts of your code. Instead of repeating the same code
everywhere, you write it once in a special helper called an aspect.
Spring will then automatically run this code wherever it's needed.
You can create this helper either using regular Java classes or by
using the @Aspect annotation.

Join Point:
A join point is just a specific point during your program's execution
—usually when a method is called. In Spring AOP, every time a
method is run, it’s considered a join point. You can use an aspect to
AOP CONCEPTS AND
TERMINOLOGY
Advice is the action that an aspect performs at certain points in
your code — like running something before, after, or around a
method. In Spring AOP, advice works like an interceptor that wraps
around the method being called.

Pointcut is a rule that decides where the advice should be


applied — for example, on all methods with a specific name. Spring
uses a special language (AspectJ expression) to define these rules.
Whenever a rule matches a method execution (called a join point),
the corresponding advice is triggered.
AOP CONCEPTS AND
TERMINOLOGY
Introduction:
In Spring AOP, you can add new methods or fields to an existing
object without changing its code. This is done by introducing a new
interface (and its implementation) to the object. For example, you
could make a bean implement an IsModified interface to help with
caching. This feature is also called an inter-type declaration in
AspectJ.
Target Object:
This is the actual object that is being affected (or advised) by one
or more aspects. It's also called the advised object. Since Spring
AOP works using proxies (wrappers around the real object), this
target is always a proxy version of the original object.
AOP CONCEPTS AND
TERMINOLOGY
AOP Proxy:
In Spring AOP, an AOP proxy is a special object that is created by the
framework to apply additional behavior (like logging or security) to
methods. This proxy wraps around the original object and makes sure
the extra logic (called advice) runs when methods are called. Spring
uses either JDK dynamic proxies or CGLIB proxies to create these
proxy objects.
Weaving:
Weaving means combining the extra logic (aspects) with your main
application code to form a single object that has both the original
behavior and the new behavior. This can happen at different times:
Compile time (when the code is being compiled)
Load time (when classes are loaded into memory)
Runtime (while the program is running)
Note : Spring AOP does this weaving at runtime, which means it adds the extra behavior
while your application is running.
AOP ADVICE
Before advice: This runs before a method is called. It can’t stop
the method from running (unless an error is thrown).

After returning advice: This runs after a method finishes


successfully (without any errors).

After throwing advice: This runs only if the method throws an


error.

After (finally) advice: This runs no matter what — whether the


method succeeds or fails.
AOP ADVICE
Around advice: it is a special type of advice in Spring AOP that
wraps around a method call. It lets you add custom code both
before and after the method runs. You can also decide whether
the original method should actually run or not. Instead, you can
return a different result or even throw an error if needed.
BEAN
A bean is a java object that is instantiated, assembled and
managed by a Spring IoC container. These beans are created using
configuration metadata supplied either by XML, annotations, or
Java code.
There are
1. Using three common
XML ways:Annotations
2. Using 3. Using Java
Configuration (@Component, @Service, Configuration
<bean id="myBean" etc.) (@Configuration,
class="com.example.My @Component @Bean )
Class" /> public class MyBean { @Configuration
// Bean logic } public class AppConfig {
@Bean
public MyBean
myBean() {
return new
MyBean();}
}
BEAN (BEAN SCOPES)
In Spring, when you create a <bean>, you can choose its
scope, which means you decide how often and when
Spring should create a new object of that bean.
If you want Spring to create a new object every time
it's needed, use the prototype scope.
If you want Spring to use the same object every time,
use the singleton scope.
Spring supports five different scopes in total, but
three of them can only be used in web applications
that are aware of the web environment.
DIFFERENT BEAN SCOPES
Singleton (default): Spring creates only one object
from the bean definition and reuses it every time from
the same container.

Prototype: Spring creates a new object each time the


bean is requested.

Request: Spring creates a new bean for each HTTP


request, and it lives only for the duration of that request.
DIFFERENT BEAN SCOPES
Session scope: A new bean is created for each user
session and stays alive as long as the session lasts.
Works only in web applications.

Application scope: A single bean is created and used


throughout the entire web application
(ServletContext). Also limited to web apps.

WebSocket scope: A new bean is created for each


SINGLETON SCOPE
When a bean is set to singleton scope, the Spring IoC container
creates only one object of that bean. This object is kept in memory
(cached), and every time you ask for that bean, Spring gives you
the same object.
By default, Spring uses singleton scope, so you don’t need to
specify it unless you want to be explicit. If you do want to declare
it, you can write it like this in the configuration file:
<!-- A bean with singleton scope -->
<bean id="..." class="..." scope="singleton">
<!-- Configuration details for this bean -->
</bean>
SINGLETON SCOPE-
EXAMPLE
Steps to Create a Simple Spring Application:
Create a Java class (HelloWorld.java) in a package
named com.example.
This class will have:
 A private variable message to hold some text.
 A setter method setMessage(String message) to assign a value to
the message variable.
 A method getMessage() that prints the message to the console.
SINGLETON SCOPE-
EXAMPLE HelloWorld.java
package com.example;
public class HelloWorld {
private String message; // a variable to store message
// This method sets the value of message
public void setMessage(String message){
this.message = message;
}
// This method displays the message on the screen
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
SINGLETON SCOPE-
EXAMPLE
MainApp.java :
package com.example;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContex
t;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("Beans.xml“);
HelloWorld objA = (HelloWorld) context.getBean("helloWorld");
objA.setMessage("I'm object A");
objA.getMessage();
HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
SINGLETON SCOPE-
EXAMPLE
MainApp.java code(What the program does):
This is a simple Java program using the Spring Framework to load
and use a bean (a Java object managed by Spring).
The class is named MainApp, and it is part of the abes package.
ApplicationContext context = new
ClassPathXmlApplicationContext("Beans.xml");
This line tells Spring to read the configuration file named
Beans.xml, which contains the definitions of the beans (objects) we
want to use.
HelloWorld objA = (HelloWorld) context.getBean("helloWorld");
This creates an object named objA of the HelloWorld class using the
bean definition with the ID "helloWorld" from Beans.xml.
SINGLETON SCOPE-
EXAMPLEobject A");
objA.setMessage("I'm
Sets a message in objA.
objA.getMessage();
Retrieves and prints the message from objA.
HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
Creates another object objB also from the same bean "helloWorld".
objB.getMessage();
Prints the message from objB.
This code loads a Spring configuration file. It retrieves a bean twice (once for objA,
once for objB) and sets a message in the first one. Then it prints messages from
both objects. Depending on the bean scope (singleton or prototype), objA and objB
may point to the same object or different ones.
SINGLETON SCOPE-
EXAMPLE
configuration file Beans.xml required for singleton scope −
<xml version = "1.0" encoding = "UTF-8">
<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 = "helloWorld" class = “com.paackage.HelloWorld" scope =
"singleton”>
</bean>
</beans>
Once you are done creating the source and bean configuration files, let us run the
application. If everything is fine with your application, it will print the following
PROTOTYPE SCOPE
If a bean is defined with prototype scope, Spring creates a new
object each time it is requested from the container.
In general:
Use prototype for beans that hold their own data (stateful).
Use singleton for beans that don't hold data and are shared
(stateless).
To set a bean as prototype in the Spring configuration file, you just
set the scope to "prototype" like this:
<!-- A bean definition with prototype scope -->
<bean id = "..." class = "..." scope = "prototype">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="myBean" class="com.example.MyClass"
PROTOTYPE SCOPE
EXAMPLE
HelloWorld.java file
package com.example;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
PROTOTYPE SCOPE
EXAMPLE MainApp.java
package com.example;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContex
t;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("Beans.xml“);
HelloWorld objA = (HelloWorld) context.getBean("helloWorld");
objA.setMessage("I'm object A");
objA.getMessage();
HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
PROTOTYPE SCOPE
EXAMPLE
configuration file Beans.xml required for prototype scope −
<?xml version = "1.0" encoding = "UTF-8"?>
<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 = "helloWorld" class = “abes.HelloWorld" scope =
"prototype”>
</bean>
</beans>
Once you are done creating the source and bean configuration files, let us run the
application. If everything is fine with your application, it will print the following message

AUTO WIRING
In Spring, we create objects (called beans) using the <bean> tag in
an XML file. If one bean needs another bean, we can connect them
manually using <constructor-arg> (for constructor injection) or
<property> (for setter injection).

But instead of connecting beans manually every time, Spring gives


us a shortcut called autowiring. It automatically finds and connects
matching beans and helpful in big projects.
EXAMPLE AUTO WIRING
// Engine.java
public class Engine {
public Engine() {
System.out.println("Engine created"); }
}
// Car.java
public class Car {
private Engine engine;
// Constructor injection

public Car(Engine engine) {


this.engine = engine;
System.out.println("Car created with engine");
}
}
EXAMPLE WITH AUTO
WIRING
<bean id="engine" class="Engine"/>
<bean id="car" class="Car" autowire="constructor"/>

Note: Here, Spring will automatically inject the engine bean into car using the
constructor. This means you don’t need to specify the constructor-arg
manually — Spring figures it out based on the constructor type.
EXAMPLE WITHOUT AUTO
WIRING
Manual Configuration in XML

<bean id="engine" class="Engine"/>


<bean id="car" class="Car">
<constructor-arg ref="engine"/>
</bean>
EXAMPLE AUTO WIRING
// Engine.java
public class Engine {
public Engine() {
System.out.println("Engine created"); }
}
// Car.java
public class Car {
private Engine engine;
// Setter method for injection
public void setEngine(Engine engine) {
this.engine = engine;
System.out.println("Car created with engine");
}
}
EXAMPLE WITH AUTO
WIRING
<bean id="engine" class="Engine"/>
<bean id="car" class="Car" autowire=“byType"/>

Note: Here, Spring will automatically inject the engine bean into car using the
setter method.
EXAMPLE WITHOUT AUTO
WIRING
Manual Configuration in XML

<bean id="engine" class="Engine"/>


<bean id="car" class="Car">
<property name=“engine” ref="engine"/>
</bean>

We changed the Car class to have a setter method (setEngine).


In the XML, we now use <property name="engine" ref="engine"/> to inject the
Engine bean into the Car bean.
This is called setter-based dependency injection in Spring.
AUTO WIRING MODES
Spring offers different ways (called autowiring modes) to
automatically provide the required dependencies to a bean. You can
choose the autowiring method by setting the autowire attribute in
the <bean/> tag of the Spring(XML) configuration file.

In other words, Spring can automatically connect one object (bean)


to another without writing extra code. This is called autowiring. You
can set this by using the autowire setting in the <bean> tag in your
XML configuration file.
AUTO WIRING LIMITATION
If there’s more than one bean of the same type, Spring may get
confused and throw an error unless you specify which one to use.

If a required bean is missing, the application might crash at runtime


instead of showing a clear compile-time error.

Autowiring is most effective when it's used consistently throughout a


project. If it's only used for a few beans while others are wired
manually, it can confuse developers. While autowiring helps reduce
the need to manually set properties or constructor arguments, you
ANNOTATION BASED
CONFIGURATION
It became possible to configure the dependency injection using
annotations. So instead of using XML to describe a bean
wiring, you can move the bean configuration into the component
class itself by using annotations on the relevant class, method, or
field declaration.
Annotation injection is performed before XML injection. Thus, the
latter configuration will override the former for properties wired
through both approaches. Annotation wiring is not turned on in the
Spring container by default. So, before we can use annotation-based
wiring, we will need to enable it in our Spring configuration file.
ANNOTATION BASED
CONFIGURATION
Consider the following configuration file in case you want to use any
annotation in your Spring application.

<?xml version = "1.0" encoding = "UTF-8"?>


<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:context = "http://www.springframework.org/schema/context"
xsi:schemaLocation =
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-
3.0.xsd">
<context:annotation-config/>
<!-- bean definitions go here -->
ANNOTATION BASED
CONFIGURATION
Once <context:annotation-config/> is configured, you can start
annotating your code to
indicate that Spring should automatically wire values into properties,
methods, and
constructors.
LIFECYCLE CALLBACKS
To interact with the container’s management of the bean lifecycle,
you can implement the Spring InitializingBean and DisposableBean
interfaces. The container callsafterPropertiesSet() for the former and
destroy() for the latter to let the bean performcertain actions upon
initialization and destruction of your beans.

Internally, the Spring Framework uses BeanPostProcessor


implementations to process anycallback interfaces it can find and
call the appropriate methods. If you need custom featuresor other
lifecycle behavior Spring does not by default offer, you can
LIFECYCLE CALLBACKS
In addition to the initialization and destruction callbacks, Spring-
managed objects may also implement the Lifecycle interface so that
those objects can participate in the startup and shutdown process, as
driven by the container’s own lifecycle.
INITIALIZATION
CALLBACKS
The org.springframework.beans.factory.InitializingBean interface lets
a bean perform initialization work after the container has set all
necessary properties on the bean. The Initializing Bean interface
specifies a single method:

void afterPropertiesSet() throws Exception;

We recommend that you do not use the InitializingBean interface,


because it unnecessarilycouples the code to Spring. Alternatively, we
suggest using the @PostConstruct annotation orspecifying a POJO
initialization method. In the case of XML-based configuration
metadata, youcan use the init-method attribute to specify the name
of the method that has a void no-argument signature. With Java
configuration, you can use the initMethod attribute of @Bean.
INITIALIZATION
CALLBACKS
Consider the following example:
<bean id="exampleInitBean" class="examples.ExampleBean" init-
method="init"/>
public class ExampleBean {
public void init()
{
// do some initialization work
}
}
INITIALIZATION
CALLBACKS
The preceding example has almost exactly the same effect as the
following example (which consists of two listings):

<bean id="exampleInitBean"
class="examples.AnotherExampleBean"/>

public class AnotherExampleBean implements InitializingBean


{
@Override
public void afterPropertiesSet()
{
// do some initialization work
}
}
DESTRUCTION CALLBACKS
Implementing the
org.springframework.beans.factory.DisposableBean interface lets a
bean get a callback when the container that contains it is destroyed.
The DisposableBean interface specifies a single method:

void destroy() throws Exception;

We recommend that you do not use the DisposableBean callback


interface, because itunnecessarily couples the code to Spring.
Alternatively, we suggest using the @PreDestroy annotation or
specifying a generic method that is supported by bean definitions.
With XML-based configuration metadata, you can use the destroy-
method attribute on the <bean/>. With Java configuration, you can
use the destroyMethod attribute of @Bean.
DESTRUCTION CALLBACKS
Consider the following definition:
<bean id="exampleInitBean“ class="examples.ExampleBean"
destroy-method="cleanup" />

public class ExampleBean {


public void cleanup()
{
// do some destruction work (like releasing pooled connections)
}
}
DESTRUCTION CALLBACKS
The preceding definition has almost exactly the same effect as the
following definition:
<bean id="exampleInitBean"
class="examples.AnotherExampleBean" />
public class AnotherExampleBean implements DisposableBean
{
@Override
public void destroy()
{
// do some destruction work (like releasing pooled connections)
}
}
BEAN CONFIGURATION
STYLE
The central artifacts in Spring’s Java configuration support
are @Configuration-annotated classes and @Bean-annotated
methods.

he @Bean annotation is used to indicate that a method instantiates,


configures, and initializes a new object to be managed by the Spring
IoC container. For those familiar with Spring’s <beans/> XML
configuration, the @Bean annotation plays the same role as
the <bean/> element. You can use @Bean-annotated methods with
any Spring @Component. However, they are most often used
with @Configuration beans.
Annotating a class with @Configuration indicates that its primary
purpose is as a source of bean definitions.
Furthermore, @Configuration classes let inter-bean dependencies be
BEAN CONFIGURATION
STYLE
@Configuration
public class AppConfig {

@Bean
public MyServiceImpl myService() {
return new MyServiceImpl();
}
}
The preceding AppConfig class is equivalent to the following
Spring <beans/> XML:

<beans>
<bean id="myService"
class="com.acme.services.MyServiceImpl"/>

You might also like