Skip to content

sagar6502/Spring_Framework

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Framework:

IoC

Spring Dependency Injection - 
		One object depend to another object. Another to another. Kind of chain dependency.
Like a good laptop makes of good parts, good parts makes of good part.

Spring dependency Container

@Component and @AutoWired in Spring Boot

Testing all unit before initiating actual test.
Or Test by separating each unit..
Without affecting actual DB or S/W, mocking the object is also there.

Maven is a popular open-source build tool developed by the Apache Group to build, publish, and deploy several projects at once for better project management.

A build tool is a script, framework, or any kind of software created specifically for a given programming language to compile code, run tests on it, or do other operations needed for a build. 


MVC

Maven as Build tool

					











Spring Framework:
Why is spring framework needed?
What is tight coupling and loose coupling?
Tight Coupling: Tight coupling occurs when two or more components in a system are highly dependent on each other. In a tightly coupled system, changes to one component often require corresponding changes to other dependent components. This makes the system less flexible, more difficult to maintain, and harder to modify without affecting other parts. If you change one part, it may lead to a chain reaction of changes in other parts, potentially introducing bugs and making the system less robust.
Tight coupling can make it challenging to reuse or replace components because they are so interdependent. It can also hinder scalability and testability since testing individual components becomes difficult due to their strong connections with other parts.
Loose Coupling: Loose coupling, on the other hand, is a design principle that promotes independence and separation between components in a system. In a loosely coupled system, each component is designed to interact with others through well-defined interfaces or abstractions, without needing to know the internal details of other components.
With loose coupling, components are more independent and can be developed, tested, and maintained separately. This makes the system more flexible and easier to modify, as changes to one component are less likely to impact other components. Loose coupling also improves code reusability, as independent components can be more easily used in other projects or scenarios.
One way to achieve loose coupling is through the use of interfaces or APIs (Application Programming Interfaces) that provide a standard way for components to interact without exposing their internal workings. By adhering to these interfaces, components can communicate effectively without tightly coupling their implementations.





Getting started with Spring framework by Building a loose Coupled Hello World Gaming App with Modern Spring Approach


	







A basic spring boot application main class has following components:

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; 

@SpringBootApplication public class LearnSpringFrameworkApplication { 	
public static void main(String[] args) { 		    SpringApplication.run(LearnSpringFrameworkApplication.class, args); 
}
 }

This code represents the main class of a Spring Boot application. Let's break it down step by step:
Package and Imports: 
The code starts with the package declaration and the necessary import statements. In this case, the application is in the default package (no package specified), and it imports the necessary classes from the org.springframework.boot package.


@SpringBootApplication Annotation:
 The @SpringBootApplication annotation is a meta-annotation that combines three other annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan. This single annotation is commonly used to indicate that the class is the main entry point of a Spring Boot application.


Main Method: 
The main method is the entry point of the Java application. When you execute the program, the Java Virtual Machine (JVM) starts by calling this method. In this case, the main method is static, meaning it belongs to the class rather than any specific instance.


SpringApplication.run(): 
Inside the main method, you have a single line of code: SpringApplication.run(LearnSpringFrameworkApplication.class, args);. This line starts the Spring Boot application by running the LearnSpringFrameworkApplication class as the primary source. The args parameter is an array of command-line arguments that you can pass to your application when running it from the command line.
@SpringBootApplication Explained:
@Configuration:
 This annotation indicates that the class contains Spring configuration beans. Spring will treat this class as a source of bean definitions.
@EnableAutoConfiguration: 
This annotation enables Spring Boot's auto-configuration mechanism, which automatically configures various aspects of the application based on the classpath and the dependencies used. It sets up the necessary beans and configurations based on sensible defaults.
@ComponentScan: 
This annotation enables component scanning, which allows Spring to automatically discover and register Spring components such as @Component, @Service, @Repository, etc., defined in the classpath. The default behavior scans the package of the annotated class (in this case, LearnSpringFrameworkApplication) and its sub-packages for components.
So, when you run the main method in this class, the Spring Boot application will start, and Spring will take care of automatically configuring the application and discovering relevant Spring components.
Overall, this simple class serves as the starting point of your Spring Boot application, enabling auto-configuration and component scanning to set up and manage your Spring beans and the application's dependencies.
	



In Java, var is a keyword introduced in Java 10 as part of the "Local Variable Type Inference" feature. It allows you to declare local variables without explicitly specifying their types. Instead, the type of the variable is inferred by the Java compiler based on the value it is assigned.

What is the difference in achieving loose coupling with Java and Spring framework?
Achieving loose coupling is a fundamental principle in both Java and the Spring framework, but they provide different approaches to achieve it:
Java Approach to Loose Coupling:
Interfaces: In Java, you can achieve loose coupling by defining interfaces for components and programming against these interfaces rather than specific implementations. This allows you to swap different implementations of the interface without affecting the code that uses it.
Dependency Injection (DI): Java provides the concept of Dependency Injection, where the dependencies of a class are injected from the outside rather than being created within the class itself. This allows components to be loosely coupled and promotes better testability and maintainability.
Spring Framework Approach to Loose Coupling:
Dependency Injection (DI): The Spring framework is built around the concept of Dependency Injection. It provides a powerful and flexible DI container that manages the creation and wiring of objects, enabling loose coupling between components. Spring's DI mechanism allows you to declare dependencies through constructor injection, setter injection, or method injection, making it easy to change and test individual components without affecting the entire application.
Inversion of Control (IoC): Spring's IoC container manages the lifecycle and configuration of beans (components), allowing you to declare the structure of your application and let Spring take care of creating and managing the objects. This promotes loose coupling because components are not responsible for creating or obtaining their dependencies; instead, the IoC container handles the dependency resolution.
Advantages of Spring for Loose Coupling:
Spring's IoC container and DI mechanism handle much of the plumbing code, reducing the need for manual dependency management in your codebase.
Spring allows you to use annotations, such as @Autowired, to automatically wire dependencies, reducing boilerplate code.
Spring's AOP (Aspect-Oriented Programming) features further promote loose coupling by separating cross-cutting concerns from the core business logic.
Spring provides a rich set of features for modularization, allowing you to create well-organized and loosely coupled applications.
In summary, while both Java and Spring provide mechanisms to achieve loose coupling, Spring provides a more comprehensive and powerful framework for dependency management and inversion of control. The Spring framework's DI container and IoC capabilities make it easier to develop highly modular, maintainable, and loosely coupled applications compared to doing so manually in pure Java.



SpringBean is an entity that constraints the implementation of spring framework

The @ComponentScan annotation is used in the Spring Framework to enable component scanning and specify the base packages that Spring should scan to find and register Spring beans automatically. Component scanning is a process by which Spring automatically detects classes annotated with stereotype annotations like @Component, @Service, @Repository, and @Controller, and registers them as beans in the application context.


In the Spring Framework, the ApplicationContext is a container that manages the lifecycle of Spring beans and provides various services to the application, including:
Dependency Injection (DI): The ApplicationContext manages the instantiation and configuration of Spring beans and performs dependency injection, allowing you to wire components together and promote loose coupling between classes.
Bean Lifecycle Management: The Spring context handles the lifecycle of beans, including their creation, initialization, and destruction, based on the specified scope of the beans.
Configuration and Properties Management: The Spring context can read configuration information from various sources (e.g., XML, Java annotations, or Java code) and manage properties or configuration values.
AOP Support: The ApplicationContext provides support for Aspect-Oriented Programming (AOP), allowing you to define cross-cutting concerns and apply them to your application.
Integration with Other Spring Features: The Spring context integrates with other features of the Spring Framework, such as Spring Security, Spring Data, Spring MVC, etc.

@Primary
Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value.
This annotation is semantically equivalent to the <bean> element's primary attribute in Spring XML.
May be used on any class directly or indirectly annotated with @Component or on methods annotated with @Bean. 

@Qualifier 
This annotation may be used on a field or parameter as a qualifier for candidate beans when autowiring. It may also be used to annotate other custom annotations that can then in turn be used as qualifiers.


 Both @Primary and @Qualifier are annotations in the Spring Framework used to handle bean injection when there are multiple candidates for autowiring. They serve different purposes and are used in different scenarios:
@Primary:
@Primary is used to indicate the primary bean to be used for autowiring when there are multiple beans of the same type.
When a bean is marked as @Primary, it becomes the default candidate for injection when there is no specific @Qualifier specified to disambiguate between multiple beans of the same type.
If there are multiple beans of the same type, but none of them are marked as @Primary, Spring will throw an exception because it cannot determine which bean to inject.
Example:
@Component
@Primary
public class PrimaryBean implements SomeInterface {
    // PrimaryBean implementation
}

@Qualifier:
@Qualifier is used to specify which bean should be injected when there are multiple beans of the same type, and none of them is marked as @Primary.
With @Qualifier, you can specify the name or value of the desired bean to be injected, allowing you to explicitly choose which bean should be used for injection.
It can be used with @Autowired, @Inject, or other injection annotations to narrow down the choice of the bean to be injected.
Example:
@Component("beanA")
public class BeanA implements SomeInterface {
    // BeanA implementation
}

@Component("beanB")
public class BeanB implements SomeInterface {
    // BeanB implementation
}

@Component
public class MyService {

    private final SomeInterface bean;

    @Autowired
    public MyService(@Qualifier("beanA") SomeInterface bean) {
        this.bean = bean;
    }

    // Other methods that use the injected bean
}

In the example above, there are two beans of type SomeInterface: BeanA and BeanB. Since neither of them is marked as @Primary, we use @Qualifier("beanA") in the MyService constructor to specify that we want BeanA to be injected.
To summarize, @Primary is used to set a default bean for injection when there are multiple candidates of the same type, while @Qualifier is used to explicitly specify which bean should be injected when there are multiple candidates, and none of them is marked as @Primary.

Three types of Dependency Injection(DI) -  Constructor, Field and Setters

In construction DI, no need of @Autowired annotation







The control of creating object is replaced from a programmer to spring framework. This is known as “Inversion of Control”









Lazy initialization is a concept used in the Spring Framework, which is a popular framework for building Java-based applications. In Spring, lazy initialization refers to the practice of deferring the creation of an object or bean until it is actually needed, as opposed to creating it eagerly during the application startup.

In the context of Spring's Inversion of Control (IoC) container and bean lifecycle management, lazy initialization means that Spring will delay the creation of a bean until the first time it is requested for use. This can help improve the application's startup time and resource usage, especially when dealing with beans that might not be needed immediately.

By default, Spring beans are eagerly initialized, meaning they are created as soon as the application context is being created. However, there might be scenarios where creating beans eagerly can be wasteful, especially if those beans are resource-intensive or might not be used throughout the entire application's lifecycle. In such cases, you can configure Spring to initialize beans lazily.

Eager initialization in the Spring Framework is the default behavior for creating beans when the application context is being created. This means that all beans defined in the Spring configuration are created and initialized as soon as the application starts up, regardless of whether they are immediately used or not. Eager initialization ensures that beans are ready for use as soon as they are needed.




Lazy initialization becomes run_time error.



@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE): This annotation is used to specify the scope of the bean. In this case, you're using the SCOPE_PROTOTYPE constant from ConfigurableBeanFactory, which indicates that the bean should have a prototype scope. A prototype-scoped bean creates a new instance every time it's requested from the Spring container, effectively giving you a new object instance for each injection or retrieval.

@Component: This annotation indicates that the class should be managed by Spring as a bean. It tells Spring to scan the class and create an instance of it to be managed within the Spring application context.

class PrototypeClass { ... } : This is the actual class definition for your Spring bean. It's a simple class named PrototypeClass.

Putting it all together, when you declare a bean with a prototype scope using the @Scope annotation, Spring will create a new instance of the PrototypeClass every time you request that bean from the application context. This is in contrast to other scopes like singleton, where a single instance of the bean is shared across the entire application context.

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method must be invoked before the class is put into service. This annotation must be supported on all classes that support dependency injection. The method annotated with PostConstruct must be invoked even if the class does not request any resources to be injected. Only one method in a given class can be annotated with this annotation. The method on which the PostConstruct annotation is applied must fulfill all of the following criteria:
The method must not have any parameters except in the case of interceptors in which case it takes an InvocationContext object as defined by the Jakarta Interceptors specification.
The method defined on an interceptor class or superclass of an interceptor class must have one of the following signatures:
 void <METHOD>(InvocationContext)
 Object <METHOD>(InvocationContext) throws Exception
 Note: A PostConstruct interceptor method must not throw application exceptions, but it may be declared to throw checked exceptions including the java.lang.Exception if the same interceptor method interposes on business or timeout methods in addition to lifecycle events. If a PostConstruct interceptor method returns a value, it is ignored by the container.
The method defined on a non-interceptor class must have the following signature:
 void <METHOD>()
The method on which the PostConstruct annotation is applied may be public, protected, package private or private.
The method must not be static except for the application client.
The method should not be final.
If the method throws an unchecked exception the class must not be put into service except in the case where the exception is handled by an interceptor.


@Target(value={METHOD})
@Retention(value=RUNTIME)
@Documented
The PreDestroy annotation is used on a method as a callback notification to signal that the instance is in the process of being removed by the container. The method annotated with PreDestroy is typically used to release resources that it has been holding. This annotation must be supported by all container-managed objects that support the use of the PostConstruct annotation except the Jakarta EE application client. The method on which the PreDestroy annotation is applied must fulfill all of the following criteria:
The method must not have any parameters except in the case of interceptors in which case it takes an InvocationContext object as defined by the Jakarta Interceptors specification.
The method defined on an interceptor class or superclass of an interceptor class must have one of the following signatures:
 void <METHOD>(InvocationContext)
 Object <METHOD>(InvocationContext) throws Exception
 Note: A PreDestroy interceptor method must not throw application exceptions, but it may be declared to throw checked exceptions including the java.lang.Exception if the same interceptor method interposes on business or timeout methods in addition to lifecycle events. If a PreDestroy interceptor method returns a value, it is ignored by the container.
The method defined on a non-interceptor class must have the following signature:
 void <METHOD>()
The method on which PreDestroy is applied may be public, protected, package private or private.
The method must not be static.
The method should not be final.
If the method throws an unchecked exception it is ignored by the container.
<dependency>
			<groupId>jakarta.inject</groupId>
			<artifactId>jakarta.inject-api</artifactId>
			<version>2.0.1</version>
</dependency>


https://docs.spring.io/spring-framework/docs/4.2.x/spring-framework-reference/html/xsd-configuration.html

<bean id="name" class = "java.lang.String">
       		 <constructor-arg value = "Sagar"/>
        </bean>
The code is an example of XML configuration for creating a Spring bean using the Spring Framework, a popular Java framework for building enterprise-level applications. Let me break down what each part of this XML configuration means:


<bean id="name" class="java.lang.String">
    <constructor-arg value="Sagar"/>
</bean>
<bean id="name" class="java.lang.String">: This part defines the bean configuration.

id="name": It assigns a unique identifier ("name") to the bean. This ID can be used to refer to this bean in other parts of your Spring application.

class="java.lang.String": It specifies the class of the bean. In this case, it's java.lang.String, which is the class representing strings in Java.

<constructor-arg value="Sagar"/>: This part sets up the constructor argument for the bean. In Java, when you create an object, you often pass values to its constructor. Here's what's happening:

<constructor-arg value="Sagar"/>: This line provides a value ("Sagar") to the constructor of the java.lang.String class.

This is similar to saying: String name = new String("Sagar"); in regular Java code.
When your Spring application starts up, it will read this XML configuration and create a Spring bean with an ID of "name" and a value of "Sagar" as specified in the constructor-arg. This bean can then be used in other parts of your application where you need a string with the value "Sagar."

In Spring, beans are the fundamental building blocks, and the Spring container manages them, allowing you to easily create, manage, and use objects within your application. The XML configuration you provided is a simple example of how you can define and set up a bean using Spring's Inversion of Control (IoC) and Dependency Injection (DI) principles.





org.springframework.stereotype.Service

@Target(value={TYPE})
@Component
@Retention(value=RUNTIME)
@Documented
Indicates that an annotated class is a "Service", originally defined by Domain-Driven Design (Evans, 2003) as "an operation offered as an interface that stands alone in the model, with no encapsulated state."
May also indicate that a class is a "Business Service Facade" (in the Core J2EE patterns sense), or something similar. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate. 

Spring Boot is an open-source Java framework developed by Pivotal (now VMware) that simplifies the process of building, deploying, and running production-grade Spring-based applications. It focuses on making it easier to create stand-alone, production-grade Spring applications with minimal configuration. Spring Boot provides a wide range of features and benefits, which include:

Auto-Configuration:
Spring Boot automatically configures various components based on the dependencies present in your project's classpath. This eliminates the need for manual configuration for most common scenarios, reducing boilerplate code.

Standalone Applications:
Spring Boot applications can be run as stand-alone JAR files, which contain an embedded web server. This makes deployment and distribution easier as you don't need to install and configure a separate web server.

Opinionated Defaults:
Spring Boot comes with sensible defaults for various configuration parameters, reducing the need for extensive configuration. These defaults are based on best practices and common use cases.

Microservices Ready:
Spring Boot is well-suited for building microservices architectures due to its lightweight nature and embedded server capabilities. It also integrates well with Spring Cloud for building distributed systems.

Production Readiness:
Spring Boot provides features like health checks, metrics, and externalized configuration, making it easier to monitor and manage your applications in production environments.

Easy Testing:
Spring Boot provides utilities for testing, including the ability to create embedded web servers for integration testing and the option to mock dependencies using annotations.



Spring Ecosystem Integration:
Spring Boot seamlessly integrates with the larger Spring ecosystem, including Spring Data, Spring Security, Spring Cloud, etc., allowing you to leverage a wide range of functionalities.

Externalized Configuration:
Spring Boot allows you to configure your application using property files, YAML files, environment variables, or command-line arguments. This helps in easily configuring your application for different environments.

Embedded Servers:
Spring Boot supports embedded web servers like Tomcat, Jetty, and Undertow. You can package your application as an executable JAR or WAR file and run it using the embedded server.

Spring Boot Actuator:
Spring Boot Actuator provides production-ready features such as health checks, metrics, and monitoring endpoints. These features help you manage and monitor your application in production.

Developer Productivity:
Spring Boot reduces the time developers spend on setting up configurations, allowing them to focus on writing application logic and delivering business value.

Wide Range of Starter Projects:
Spring Boot offers a collection of starter projects that provide pre-configured setups for different types of applications, like web applications, data-driven applications, messaging applications, etc.

Overall, Spring Boot's key focus is on simplicity, rapid development, and the ability to quickly create robust and production-ready applications using the Spring framework.





Differences between spring and spring boot
Spring and Spring Boot are both frameworks developed by Pivotal (now VMware) for building Java applications, but they serve slightly different purposes and have distinct features. Here are the main differences between Spring and Spring Boot:
Configuration:
Spring: In Spring, you need to configure various components using XML configuration files, Java-based configuration classes (using annotations), or a combination of both.
Spring Boot: Spring Boot aims to minimize the need for extensive configuration. It provides auto-configuration, which automatically configures many components based on the project's classpath and dependencies. Configuration can be further simplified using property files, YAML files, environment variables, or command-line arguments.
Standalone Applications:
Spring: Spring applications often require external web servers, servlet containers, or application servers for deployment.
Spring Boot: Spring Boot applications are designed to be stand-alone. They include an embedded web server (Tomcat, Jetty, or Undertow) so that you can run them as executable JAR files without the need for an external server.
Opinionated Defaults:
Spring: Spring provides flexibility in configuration, but this flexibility can also lead to configuration complexities.
Spring Boot: Spring Boot adopts opinionated defaults and conventions, reducing the need for extensive configuration. It makes choices for you based on best practices, allowing developers to get started quickly.
External Dependencies:
Spring: Developers need to explicitly manage and include dependencies in their projects, which may involve dealing with version conflicts and dependency management.
Spring Boot: Spring Boot provides a set of "starter" projects that include predefined dependencies. These starters manage dependencies and ensure compatibility between libraries, reducing the effort required for dependency management.
Auto-Configuration:
Spring: Spring applications often require manual configuration of components and beans, which can be time-consuming.
Spring Boot: Spring Boot's auto-configuration feature automatically configures common components and beans based on the project's dependencies. This reduces the need for explicit configuration.
Production-Ready Features:
Spring: Spring provides a foundation for building applications, but additional libraries and configurations are required for production readiness.
Spring Boot: Spring Boot includes production-ready features out of the box, such as health checks, metrics, monitoring endpoints, and externalized configuration. This makes it easier to manage and monitor applications in production environments.
Developer Productivity:
Spring: Developers need to spend more time setting up configurations, which can slow down development.
Spring Boot: Spring Boot's focus on simplicity and convention over configuration allows developers to be more productive, as they can quickly create functional applications without getting bogged down in configuration details.
In summary, Spring Boot is built on top of the Spring framework and aims to simplify the process of building and deploying Spring applications. It achieves this by providing opinionated defaults, auto-configuration, embedded servers, and production-ready features, all of which contribute to faster development and deployment cycles. Spring, on the other hand, provides more flexibility in configuration and is suitable for more complex scenarios where specific configurations and setups are required.

@RestController is an annotation in the Spring Framework (including Spring Boot) that is used to define a class as a RESTful controller. In other words, it indicates that the class will handle incoming HTTP requests and produce responses in a RESTful manner. This annotation combines the @Controller and @ResponseBody annotations, simplifying the process of creating RESTful APIs.





About

Learning and implementing SpringFramework

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages