0% found this document useful (0 votes)
4 views12 pages

Java Configuration Spring 12

The document provides a detailed explanation of a Java Spring configuration using annotations, specifically focusing on the UseBeans and AppConfig classes. It describes how to create a Spring IoC container, retrieve beans, and the roles of annotations like @Configuration and @ComponentScan in managing bean definitions. Additionally, it discusses the differences between @Bean and @Component annotations for bean creation and configuration within Spring applications.

Uploaded by

yograj.tripathi
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)
4 views12 pages

Java Configuration Spring 12

The document provides a detailed explanation of a Java Spring configuration using annotations, specifically focusing on the UseBeans and AppConfig classes. It describes how to create a Spring IoC container, retrieve beans, and the roles of annotations like @Configuration and @ComponentScan in managing bean definitions. Additionally, it discusses the differences between @Bean and @Component annotations for bean creation and configuration within Spring applications.

Uploaded by

yograj.tripathi
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/ 12

Java Configuration Spring

Date: 20/09/2024

UseBeans.java

java

Copy code

package in.scalive.app;

import in.scalive.conf.AppConfig; // Importing configuration class

import in.scalive.demobeans.Car; // Importing Car bean

import in.scalive.samplebeans.Student; // Importing Student bean

import org.springframework.context.ApplicationContext;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class UseBeans {


2

public static void main(String[] args) {

// Creating the Spring IoC container by providing the AppConfig class

ApplicationContext container = new


AnnotationConfigApplicationContext(AppConfig.class);

// Retrieving the Student bean from the container and invoking the display()
method

Student s1 = (Student) container.getBean("student");

s1.display();

// Retrieving the Car bean from the container and invoking the show() method

Car c1 = (Car) container.getBean("car");

c1.show();

AppConfig.java

java

Copy code

package in.scalive.conf;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;
3

// This class tells Spring where to look for beans

@Configuration

@ComponentScan(basePackages = {"in.scalive.demobeans", "in.scalive.samplebeans"})

public class AppConfig {

Directory Structure

src

└── in

└── scalive

├── app

│ └── UseBeans.java

├── conf

│ └── AppConfig.java

├── demobeans

│ └── Car.java

└── samplebeans

└── Student.java

How It Works:

1. UseBeans.java: This is your main application class where you initialize the Spring
context (ApplicationContext) with the configuration provided in AppConfig. It
retrieves beans like Student and Car from the container and invokes methods on them.
4

2. AppConfig.java: This is your Spring configuration class. It's annotated with


@Configuration to specify that it's a configuration class, and @ComponentScan tells
Spring to scan the specified packages for beans to register (in this case,
in.scalive.demobeans and in.scalive.samplebeans).

When you run the program:

● Spring automatically scans for any classes annotated with @Component (or similar) in
the provided packages, creates instances (beans), and makes them available in the
ApplicationContext.

1. ApplicationContext container = new


AnnotationConfigApplicationContext(in.scalive.conf.AppCon
fig.class);
This line is creating a Spring IoC (Inversion of Control) container, which is responsible
for managing your application's beans (objects). Here's what happens behind the
scenes:

● ApplicationContext: This is an interface provided by Spring, which is


responsible for managing the lifecycle and dependencies of beans. It's the heart
of Spring's IoC container.
● AnnotationConfigApplicationContext: This is a specific implementation
of the ApplicationContext interface. It scans for configurations that are
defined using annotations like @Configuration, @Component, @Bean, etc.
● in.scalive.conf.AppConfig.class: This is your configuration class.
Spring looks at this class to find the beans to be managed. The AppConfig
class is annotated with @Configuration, so Spring knows it's a configuration
class.

What happens behind the scenes?


5

● Configuration class detection: When you pass AppConfig.class, Spring scans


it to find any configuration-related annotations (@Configuration and
@ComponentScan in this case).
● Bean definitions and scanning: The @ComponentScan annotation tells Spring to
scan specific packages (in your case, "in.scalive.demobeans" and
"in.scalive.samplebeans") for classes annotated with @Component,
@Service, @Repository, etc. Spring treats these classes as beans, which will
be managed by the IoC container.
● Bean instantiation: Once the scanning is done, Spring creates instances of these
beans and manages their lifecycle. For example, Student and Car will be
automatically instantiated and stored in the ApplicationContext.

After Spring has set up the container (i.e., the


AnnotationConfigApplicationContext), it's ready to provide the required beans
when asked.

2. Component and Configuration in AppConfig

Let's break down your AppConfig class:

java

Copy code

○ @Configuration
○ @ComponentScan(basePackages =
{"in.scalive.demobeans","in.scalive.samplebeans"})
○ public class AppConfig {
○ }

@Configuration:

● This annotation tells Spring that this class contains configuration information for
the application. It is similar to an XML configuration file, but in Java.
● By marking this class as @Configuration, Spring knows to process it as a
source of bean definitions.
6

@ComponentScan(basePackages = {"in.scalive.demobeans",
"in.scalive.samplebeans"}):

● This annotation tells Spring which packages to scan for beans.


● Spring will look through these specified packages (in.scalive.demobeans,
in.scalive.samplebeans) and find classes annotated with @Component,
@Service, @Controller, @Repository, etc. These annotated classes will
automatically be registered as beans in the Spring IoC container.

3. register() and refresh()

These methods are part of Spring’s internals when managing the ApplicationContext.

● register(): Registers one or more configuration classes in the context. You


don't see this directly because AnnotationConfigApplicationContext
implicitly registers the class you pass in its constructor (AppConfig.class in
your case).
● refresh(): This method tells the Spring container to refresh the context and
initialize beans. Again, it is implicitly called within the
AnnotationConfigApplicationContext when the context is created.

4. After the container is created:

When you create the ApplicationContext, Spring automatically performs the


following:

1. Bean Scanning: Scans the specified packages (in.scalive.demobeans and


in.scalive.samplebeans) to find all eligible classes annotated with
@Component or related annotations.
2. Bean Instantiation: Creates the necessary beans (like Student and Car) based
on the classes found during scanning.
3. Dependency Injection: If any of these beans have dependencies (via constructor
or setter injection), Spring will inject them automatically.
4. Lifecycle Management: Spring manages the entire lifecycle of these beans, from
instantiation to destruction.

Example:

java
7

Copy code

○ Student s1 = (Student) container.getBean("student");


○ s1.display();

● Here, you're asking the ApplicationContext for a bean named student.


● The bean is returned by Spring, which has already created it (thanks to
@Component annotation in the Student class).
● You then call the display() method of Student.

Summary of Flow:

1. You define AppConfig with @Configuration and @ComponentScan, which


tells Spring where to look for beans.
2. The ApplicationContext is created using
AnnotationConfigApplicationContext, which automatically registers the
configuration class and scans the specified packages for beans.
3. The container manages the lifecycle of these beans.
4. You fetch the beans from the container using container.getBean().

This entire process is happening automatically due to Spring’s annotations and its
built-in IoC and DI (Dependency Injection) capabilities.

Topic: Using @Bean Annotation

Key Points:

● @Bean Annotation:

○ Used to create beans without @Component and @ComponentScan

annotations.
8

○ Provides flexibility in bean definition and configuration.

Additional Notes:

● The image likely comes from a presentation or lecture related to Spring

framework.

● The presenter's name is Sharma Computer Academy.

● The presentation is being recorded using Scalive.

The @Bean annotation is a key feature in the Spring framework used to declare beans in a

configuration class. Let me elaborate on it and clarify the differences between @Bean,

@Component, and @ComponentScan.

Key Differences:

1. @Bean vs. @Component:

○ @Bean:

■ This annotation is used to define and configure beans within a method of

a class annotated with @Configuration.

■ It provides more flexibility for creating beans where custom initialization or

configurations are required.

■ For example, you may want to create a bean with specific parameters or

have control over its instantiation logic.

Example:

java
9

Copy code

@Configuration

public class AppConfig {

@Bean

public Car car() {

return new Car("Toyota");

■ This approach does not require @ComponentScan.

○ @Component:

■ This annotation is used at the class level to indicate that the class is a

Spring-managed component (i.e., a bean).

■ Spring will automatically detect and register it as a bean when scanning

the package.

■ However, the automatic scanning for @Component requires

@ComponentScan to specify where Spring should search for these

beans.

Example:

java

Copy code
10

@Component

public class Car {

public Car() {

// Constructor logic

2. @ComponentScan:

○ This annotation is used to tell Spring which packages to scan for @Component,

@Controller, @Service, or @Repository annotations.

○ Without @ComponentScan, Spring won’t automatically detect and register

classes annotated with @Component from other packages.

When to Use @Bean:

● You use @Bean when you want more control over the instantiation of your bean. This is

particularly useful when:

○ You need to pass parameters to a constructor.

○ You need to configure some properties manually before creating the bean.

○ You want to use an external library or class that cannot be annotated with

@Component.

When to Use @Component and @ComponentScan:


11

● If you just want Spring to automatically detect beans, you can annotate classes with

@Component, and use @ComponentScan in your configuration class to register them.

Example of Combining Both:

Copy code

@Configuration

@ComponentScan(basePackages = {"in.scalive.demobeans"})

public class AppConfig {

@Bean

public Car customCar() {

return new Car("Custom Brand");

● In this example, Spring will scan the in.scalive.demobeans package for

@Component annotated beans, and the customCar() method explicitly declares a Car

bean.
12

You might also like