Chapter 15 - Spring Core Flashcards

1
Q

What is spring framework?

A

“The Spring framework is an open-source, lightweight, and comprehensive framework for building enterprise-level Java applications. It simplifies the development of complex Java applications by providing solutions to common challenges and promoting best practices. Key features of the Spring framework include:

Inversion of Control (IoC): Spring’s IoC container manages the lifecycle and dependencies of application components, allowing for loosely coupled and easily testable code.

Dependency Injection (DI): Spring supports DI, enabling the injection of dependencies into components, making the code modular and flexible.

Aspect-Oriented Programming (AOP): Spring incorporates AOP to separate cross-cutting concerns like logging and security from the core application logic.

Modularity: Spring is organized into various modules, each addressing specific concerns, which can be used selectively based on your application’s needs.

Simplified Data Access: Spring offers a consistent and user-friendly approach to database operations, abstracting low-level details.

Integration: Spring seamlessly integrates with various technologies and frameworks, making it suitable for a wide range of application types.

Testing Support: Spring’s design principles, such as IoC and DI, make unit testing and mocking of components straightforward.

Spring Boot: A part of the Spring ecosystem, Spring Boot simplifies the creation of production-ready applications by providing conventions and auto-configurations.

Community and Ecosystem: Spring has a thriving community and extensive ecosystem of third-party libraries, tools, and resources.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Spring modules

A

The Spring Framework is divided into modules. Applications can choose which modules they need. At the heart are the modules of the core container, including a configuration model and a dependency injection mechanism. Beyond that, the Spring Framework provides foundational support for different application architectures, including messaging, transactional data and persistence, and web. It also includes the Servlet-based Spring MVC web framework and, in parallel, the Spring WebFlux reactive web framework.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

explain detailed Spring Architecture (its modules)

A

Core Container
Core and Beans Modules:

Dependency: spring-core, spring-beans
Description: Provides IoC and Dependency Injection features, including BeanFactory.

Context Module:

Dependency: spring-context
Description: Builds on Core and Beans, providing a framework-style means to access objects, support for internationalization, event-propagation, and more.

Expression Language Module:

Dependency: spring-expression
Description: Provides a powerful expression language for querying and manipulating an object graph at runtime.
Data Access/Integration

JDBC Module:

Dependency: spring-jdbc
Description: Provides a JDBC-abstraction layer to simplify database access.
ORM Module:

Dependency: spring-orm
Description: Integration layers for popular ORM APIs like JPA, Hibernate.
OXM Module:

Dependency: spring-oxm
Description: Supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX, and XStream.
JMS Module:

Dependency: spring-jms
Description: Contains features for producing and consuming messages.
Transaction Module:

Dependency: spring-tx
Description: Supports programmatic and declarative transaction management.
Web

Web Module:

Dependency: spring-web
Description: Provides basic web-oriented integration features such as multipart file-upload and IoC container initialization.
Web Servlet Module:

Dependency: spring-webmvc
Description: Contains Spring’s MVC framework for web applications.
Web Reactive Module:

Dependency: spring-webflux
Description: Reactive-stack web framework introduced in Spring Framework 5.0.
AOP and Instrumentation
AOP Module:

Dependency: spring-aop
Description: Provides an aspect-oriented programming implementation, defining method-interceptors and pointcuts.
Aspects Module:

Dependency: spring-aspects
Description: Integration with AspectJ.
Instrumentation Module:

Dependency: spring-instrument
Description: Provides class instrumentation support and classloader implementations for certain application servers.

Test
Test Module:
Dependency: spring-test
Description: Supports testing of Spring components with JUnit or TestNG, providing consistent loading of ApplicationContexts and mock objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Inversion of Control (IoC)

A

inversion of Control (IoC) is a fundamental concept in the Spring Framework, and it represents a design principle that addresses the organization of application components and their relationships. IoC is often referred to as the “core” of the Spring Framework because it fundamentally changes the way components are created, managed, and interact with each other.

Here’s an explanation of Spring’s IoC:

Traditional Control Flow: In traditional Java application development, you, as the developer, typically control the flow of your program. This means you decide when and how to create objects and manage their lifecycles. For example, you might instantiate objects directly within your classes and manage their dependencies, leading to tightly coupled and often hard-to-maintain code.

Inversion of Control: Spring’s Inversion of Control reverses this control flow. In an IoC container, the responsibility for creating and managing objects (components) is taken away from your application code and handed over to the container itself. The container manages the object lifecycle, including creating, configuring, and destroying objects.

Components and Beans: In the context of Spring, objects managed by the IoC container are often referred to as “components” or “beans.” These are Java objects that serve as building blocks for your application.

Dependency Injection (DI): A crucial part of IoC is Dependency Injection. Instead of your components creating their dependencies, the IoC container injects the necessary dependencies into the components. This promotes loose coupling, as components don’t need to be aware of how their dependencies are created or configured.

Configuration: Spring uses configuration metadata to define the relationships between components. This metadata can be provided in various ways, including XML configuration files, Java annotations, or Java-based configuration classes. The configuration specifies which components should be managed by the container and how they are related.

Advantages of IoC: The main advantage of IoC is that it leads to more modular, maintainable, and testable code. It also allows for greater flexibility, as you can change the configuration without altering the application code. IoC promotes best practices and separation of concerns, making the codebase cleaner and easier to extend and maintain.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Application Context

A

ApplicationContext represents the Spring IoC container that holds all the beans created by the application. It is responsible for instantiating, configuring, and creating the beans. Additionally, it gets the beans’ information from configuration metadata provided in XML or Java.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are beans?

A

In the context of the Spring Framework, a “bean” is a fundamental concept that refers to an object that is created, managed, and wired together by the Spring container. Beans are the building blocks of a Spring application, and they represent the various components and objects that make up your application’s architecture. Here are some key points about beans:

Java Objects: Beans are essentially Java objects or instances of Java classes that are managed by the Spring container. These objects can be of any class or type, and they are typically the core components of your application, such as services, data access objects, controllers, and more.

Managed by Spring: Spring manages the lifecycle of beans, including their creation, initialization, and destruction. This management relieves developers from manually creating and managing objects and their dependencies, following the principle of Inversion of Control (IoC).

Configurable: Beans are highly configurable. You can define their properties, relationships, and behaviors in configuration files (XML or Java-based) or through annotations. This configuration allows you to specify how beans are created, what their dependencies are, and how they interact with other beans.

Dependency Injection: One of the key features of beans is that they can have dependencies on other beans, and Spring facilitates the injection of these dependencies. This is often achieved through constructor injection or setter injection, ensuring that beans collaborate effectively.

Singleton or Prototype: Beans can have different scopes. The most common scopes are singleton and prototype. Singleton beans have a single instance shared across the entire application, while prototype beans create a new instance each time they are requested.

Spring Container: Beans are created and managed within the Spring container, which is typically represented by the ApplicationContext. The Spring container is responsible for instantiating and configuring beans, managing their lifecycle, and handling their dependencies.

Bean Naming: Each bean has a unique name or ID within the Spring container, allowing you to reference and retrieve specific beans when needed.

Testability: Spring’s support for dependency injection and bean configuration makes it easier to write unit tests for your application components. You can inject mock or test-specific beans for testing purposes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Dependency Injection

A

Dependency injection (DI) is a process whereby objects define their dependencies (that is, the other objects with which 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) of the bean itself controlling the instantiation or location of its dependencies on its own by using direct construction of classes or the Service Locator pattern. Code is cleaner with the DI principle, and decoupling is more effective when objects are provided with their dependencies. The object does not look up its dependencies and does not know the location or class of the dependencies. As a result, your classes become easier to test, particularly when the dependencies are on interfaces or abstract base classes, which allow for stub or mock implementations to be used in unit tests

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Constructor-based Dependency Injection

A

Constructor-based dependency injection is a design pattern used in software development, particularly in object-oriented programming and specifically in the context of inversion of control (IoC) containers. In this pattern, dependencies required by a class are provided through its constructor.

Here’s how it typically works:

Class Dependencies: A class (let’s call it ClassA) requires instances of other classes or objects to perform its tasks. These dependencies are required for ClassA to function properly.

Constructor Parameterization: Instead of creating instances of these dependencies within ClassA, the class defines a constructor that accepts these dependencies as parameters. For example:

java
Copy code
public class ClassA {
private DependencyClass dependency;

public ClassA(DependencyClass dependency) {
    this.dependency = dependency;
}

// ClassA methods that use the dependency... }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

constructor argument resolution

A

In the Spring framework, constructor argument resolution is a key aspect of dependency injection. Spring offers multiple ways to handle constructor-based dependency injection, and it’s commonly achieved using the @Autowired annotation or XML configuration.
Consider a Car class that depends on an Engine class:

java
Copy code
public class Car {
private String make;
private String model;
private Engine engine;

public Car(String make, String model, Engine engine) {
    this.make = make;
    this.model = model;
    this.engine = engine;
}

// Other methods and functionalities of the Car class... } Assuming that Engine is another Spring-managed bean:

java
Copy code
public class Engine {
private String type;

public Engine(String type) {
    this.type = type;
}

// Other methods and functionalities of the Engine class... } To enable constructor-based dependency injection in Spring, you can use @Autowired on the constructor of Car:

java
Copy code
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Car {
private String make;
private String model;
private Engine engine;

@Autowired
public Car(String make, String model, Engine engine) {
    this.make = make;
    this.model = model;
    this.engine = engine;
}

// Other methods and functionalities of the Car class... } When Spring initializes the Car bean, it identifies the constructor annotated with @Autowired and resolves the dependencies by finding beans that match the parameter types (make, model, Engine). It then injects those dependencies into the constructor.

In the Spring configuration, you define the Engine bean:

java
Copy code
import org.springframework.stereotype.Component;

@Component
public class Engine {
private String type;

public Engine(String type) {
    this.type = type;
}

// Other methods and functionalities of the Engine class... }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Constructor injection vs setter injection vs interface injection

A

Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency.
 Immutability: Constructor Injection supports immutability. Setter and Field Injection do not support immutability.
 State Safety: Constructor Injection – The object is instantiated to a full state or is not instantiated at all. Setter Injection – Consumer uses no-arg constructor, and there is a possibility of calling one of the setters or call some setters twice. (copy-paste bugs). Field Injection – Consumer uses no-arg constructor. There is no valid way to set state of the object. Only option is to use Reflection to set the private fields.

Constructor Injection is recommended in general.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Application context or bean factory?

A

In most modern Spring applications, you typically use the Application Context rather than the Bean Factory because the Application Context includes all the features and capabilities of the Bean Factory and offers several additional features that are often essential in real-world application development. As a result, the Application Context is more commonly used.

Here are some reasons to use the Application Context over the Bean Factory:

Advanced Features: The Application Context provides advanced features such as internationalization, event propagation, AOP (Aspect-Oriented Programming) support, and more. These features are often needed in complex, real-world applications.

Flexible Configuration: The Application Context supports various configuration sources, including XML configuration files, Java-based configuration classes, and annotations. This flexibility allows you to choose the configuration style that best suits your project.

Lazy Initialization: While the Bean Factory typically initializes beans on-demand (lazy initialization), the Application Context allows you to configure beans to be lazily initialized if needed. You have more control over the initialization behavior.

Profiles: The Application Context supports the concept of profiles, which allows you to define different configurations for different environments (e.g., development, testing, production). This is crucial for managing environment-specific settings.

Integration: The Application Context integrates seamlessly with other Spring features and modules, such as Spring Security, Spring Data, and Spring Web. It provides a comprehensive environment for building sophisticated applications.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Bean Factory

A

A Bean Factory is one of the central components in the Spring Framework responsible for managing and controlling the lifecycle of Spring beans (components). It is a part of the Inversion of Control (IoC) container in Spring. The Bean Factory serves as the fundamental container for creating, configuring, and managing beans in a Spring application.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Profiles

A

In Spring, profiles are a feature that allows you to define different configurations for your application based on specific runtime environments or scenarios. Profiles are useful when you need to customize your application’s configuration to suit various deployment or testing scenarios. They help ensure that your application behaves differently in different environments without having to modify your application code.

Here’s how profiles work in Spring:

Defining Profiles:
You can define profiles in your Spring configuration, typically using XML or Java-based configuration. For example, you might have profiles for “development,” “testing,” and “production.” Each profile is given a name or identifier.

xml
Copy code

<beans>
<!-- Development-specific bean definitions -->
</beans>

<beans>
<!-- Testing-specific bean definitions -->
</beans>

<beans>
<!-- Production-specific bean definitions -->
</beans>

Activating Profiles:
Profiles can be activated in different ways, depending on your application’s runtime environment:

In an XML configuration file, you can use the <beans> element's profile attribute to specify the active profile(s).
In Java-based configuration classes, you can use the @Profile annotation to associate a class or method with a profile.
Profiles can also be activated programmatically by setting the spring.profiles.active property when launching your application. For example, you can set it in the application's properties file.
Profile-Specific Configuration:
You define specific configuration, including bean definitions and property values, within the scope of each profile. When a profile is activated, only the beans and configuration associated with that profile are loaded and used by the application.</beans>

Default Profile:
You can define a default profile that is active when no specific profiles are explicitly activated. This provides a fallback configuration when no profile is specified.

Using Profiles:
In your application code, you can refer to beans defined in profile-specific configurations as needed. Spring will load the appropriate beans based on the active profile.

Switching Profiles:
You can switch profiles by changing the active profile(s) when launching your application. This allows you to use different configurations for different environments or scenarios.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Spring expression Language

A

The Spring Expression Language (SpEL) is a powerful expression language that provides a standardized way to access and manipulate objects within the Spring Framework. SpEL is used primarily in the context of Spring applications, allowing you to perform various operations on beans and their properties, invoke methods, and evaluate expressions. Here are some key aspects of SpEL:

Accessing Bean Properties:

SpEL enables you to access bean properties and their values, similar to traditional Java property access but with a more concise syntax.
For example, you can use #{beanName.property} to access a property of a specific bean.
Mathematical and Logical Operations:

SpEL supports mathematical and logical operations, allowing you to perform calculations, comparisons, and logical evaluations within expressions.
For example, #{5 + 3}, #{value > 10}, and #{true && false} are all valid expressions.
Method Invocation:

You can call methods on objects within SpEL expressions. This is particularly useful for invoking custom methods on beans.
For example, #{userService.getUserDetails()} can be used to call the getUserDetails method of a userService bean.
Conditional Expressions:

SpEL provides conditional expressions using the ? : ternary operator, allowing you to make decisions within expressions.
For example, #{user.age >= 18 ? ‘Adult’ : ‘Minor’} evaluates the age of a user and returns “Adult” or “Minor” accordingly.
Collection Access:

You can access elements of collections and arrays using SpEL.
For example, #{myList[0]} retrieves the first element of a list named myList.
Object Type Detection:

SpEL allows you to determine the type of an object using the T operator, making it easier to perform type checks.
For example, #{T(java.util.List).class} retrieves the Class object for the List type.
Relational Operators:

SpEL supports relational operators for comparing values.
For example, #{user.age > 30} checks if the age property of a user bean is greater than 30.
String Concatenation:

You can concatenate strings using the + operator.
For example, #{‘Hello, ‘ + user.name} combines the string “Hello, “ with the name property of a user bean.
Bean References:

SpEL allows you to reference other beans using @ symbol. For example, @userService.getUserDetails() references the userService bean and invokes its getUserDetails method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Proxies

A

In Spring Framework, proxies are a fundamental concept used to implement aspects of Aspect-Oriented Programming (AOP). Proxies are an essential part of AOP, which allows you to separate cross-cutting concerns (e.g., logging, security, transaction management) from your core application logic. Proxies enable the interception of method invocations on Spring beans, allowing you to add additional behavior before, after, or around the method calls. Here’s how proxies work in Spring:

Target Object:

The target object is the actual object you want to invoke methods on. It is typically a Spring bean containing the core application logic.
Advice:

Advice is the additional behavior or logic that you want to apply before, after, or around the invocation of methods on the target object. Advice is implemented as a separate component.
Aspect:

An aspect is a module that encapsulates the advice and the pointcuts. A pointcut defines which method invocations should trigger the advice.
Proxy:

A proxy is a dynamically generated object that wraps the target object. When you invoke a method on the proxy, it delegates the call to the target object. However, it also allows the advice to be applied before or after the method invocation, based on the configured pointcut.
There are two main types of proxies used in Spring:

JDK Dynamic Proxies:

JDK dynamic proxies are created using the java.lang.reflect.Proxy class and the java.lang.reflect.InvocationHandler interface.
To use JDK dynamic proxies, the target object must implement one or more interfaces, and the proxy is created dynamically at runtime.
These proxies work for interfaces only and are created using Java’s built-in reflection capabilities.
CGLIB Proxies:

CGLIB (Code Generation Library) proxies are generated by the CGLIB library. They are used when the target object does not implement any interfaces.
CGLIB generates subclasses of the target object’s class, which override the target methods to add the advice logic. These subclasses are used as proxies.
CGLIB proxies can be used for any class, not just those implementing interfaces.
Here’s how you configure and use proxies in Spring:

Define an aspect containing advice and a pointcut.
Configure the aspect and associate it with a Spring bean using annotations or XML configuration.
Specify the proxy type (JDK dynamic or CGLIB) and the target object for the Spring bean.
When you invoke a method on the bean, the proxy is used, and the advice is applied based on the defined pointcut.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are beans?

A

In software development, especially in the context of Java and frameworks like Spring, “beans” refer to objects that are managed by an inversion of control (IoC) container. These objects are created, configured, and managed by the container and are used to represent various components and services within an application.

Key characteristics of beans:

Managed Objects: Beans are typically Java objects managed by a framework or container. In Spring, for instance, beans are created and managed by the Spring IoC container.

Configuration: Beans are often defined in configuration files (XML, Java annotations, or Java code) that specify their creation, properties, and relationships with other beans.

Lifecycle Management: The container manages the lifecycle of beans, including their creation, initialization, and eventual destruction (when the application context is closed).

Dependency Injection: Beans often rely on dependency injection for the management of their dependencies. This means that a bean can depend on other beans or resources, and these dependencies are injected into the bean by the IoC container.

In the context of the Spring framework:

Java Classes as Beans: In Spring, any Java class can be a bean. By default, Spring manages these beans within an application context, allowing them to be easily created, wired together, and managed by the Spring container.

Bean Configuration: Beans in Spring can be configured through XML-based configuration files, Java-based configuration classes, or using annotations like @Component, @Service, @Repository, or @Controller.

Dependency Injection with Beans: Spring facilitates dependency injection, allowing beans to declare their dependencies, which are then injected into them by the container, often via constructor injection, setter injection, or autowiring.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Bean Scopes

A

In Spring Framework, bean scopes determine the lifecycle and visibility of Spring beans, which are the components managed by the Spring IoC container. Spring provides several predefined bean scopes that allow you to control how beans are created, cached, and destroyed in your application. Understanding and choosing the appropriate bean scope is important, as it affects the behavior and performance of your application. Here are the main bean scopes in Spring:

Singleton (default):

In the Singleton scope, Spring creates and manages a single instance of the bean for the entire application context.
All requests for the bean return the same instance, and it is cached for the lifetime of the application context.
This is the default scope and is suitable for stateless, thread-safe beans that can be shared across the application.
Prototype:

In the Prototype scope, a new instance of the bean is created every time it is requested from the container.
Each request for the bean results in a fresh instance, and there is no caching.
Use Prototype scope when you want a new, independent instance of a bean for each request or interaction, making it suitable for stateful, non-thread-safe beans.
Request:

The Request scope is typically used in a web-based environment, such as a Spring Web application.
A new instance of the bean is created for each HTTP request, and the bean is destroyed when the request ends.
This ensures that each HTTP request has its own isolated instance of the bean.
Session:

The Session scope, like Request scope, is commonly used in web applications.
A new instance of the bean is created for each user session, and the bean is destroyed when the user’s session ends.
This allows you to maintain user-specific state throughout their session.
Global Session (Portlet Scope):

The Global Session scope is similar to Session scope, but it is used in the context of portlet-based applications.
It allows you to manage a single instance of a bean for the entire user session across multiple portlets in a portal environment.
Application (available in web environments):

The Application scope is used in web applications. A single instance of the bean is created for the entire application context and is shared among all users.
The bean is destroyed when the web application is shut down or undeployed.
This scope is useful for caching application-wide data.
WebSocket (available in web environments):

The WebSocket scope is designed for use in Spring WebSocket applications.
A single instance of the bean is created for each WebSocket session, ensuring that each WebSocket session has its own instance.
To specify a bean’s scope in Spring, you can use annotations like @Scope or configure it in XML-based configuration. For example, with @Scope, you can annotate a bean definition like this:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Component Scanning

A

Component scanning, also known as auto component scanning or automatic bean discovery, is a feature in the Spring Framework that allows you to automatically discover and register Spring components, such as beans, in your application context without explicitly defining them in configuration files. This feature simplifies the configuration and management of Spring beans by eliminating the need to manually configure every bean. Instead, you annotate your classes with specific annotations, and Spring automatically identifies and registers them as beans. Here’s how component scanning works:

Annotation-Based Configuration:

To enable component scanning, you need to configure your Spring application context to scan specific packages for classes marked with relevant annotations.
Annotations:

Spring provides several annotations that are used to indicate that a class should be treated as a Spring component (bean). The most commonly used annotations are:
@Component: The most generic annotation indicating that a class is a Spring-managed component.
@Service: Used to annotate service classes.
@Repository: Used to annotate classes that interact with the database or other data sources.
@Controller: Used to annotate classes that handle web requests in a Spring MVC application.
@Configuration: Used to define Java-based Spring configurations.
Scan Packages:

You specify the base packages to scan for annotated components in your Spring application context configuration.
Auto-Discovery:

During application startup, Spring scans the specified packages and identifies classes annotated with the relevant annotations.
It registers these classes as Spring beans in the application context, making them available for dependency injection and other Spring features.
Here’s an example of enabling component scanning in a Spring configuration class:

java
Copy code
@Configuration
@ComponentScan(basePackages = “com.example”)
public class AppConfig {
// Other configuration, beans, and settings can be defined here
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Bean Lifecycle

A

In the Spring Framework, the lifecycle of a Spring bean refers to the sequence of events and methods that occur during the creation, initialization, usage, and potential destruction of a bean managed by the Spring container. Understanding the bean lifecycle is important for properly managing the state and behavior of beans in your Spring application. The bean lifecycle consists of several key phases and callback methods:

Instantiation:

During the instantiation phase, Spring creates an instance of a bean using its constructor. This is typically done by calling the default constructor of the bean’s class.
Populating Properties:

After the bean is instantiated, Spring populates the bean’s properties, either through setter methods or field injection, using the values specified in the bean configuration.
Bean Post-Processing (Initialization Callbacks):

Before a bean is fully initialized and made available for use, Spring allows for bean post-processing. This phase involves invoking callback methods, such as init-method if configured, which can contain custom initialization logic. These methods are often used for tasks like opening database connections, setting up resources, or performing other setup operations.
Initialization:

The afterPropertiesSet method (if the bean implements the InitializingBean interface) and any custom init-method configured in the bean’s definition are invoked. This is the point where you can perform bean-specific initialization tasks.
Bean Usage:

Once the bean is fully initialized, it can be used within the application. It’s important to note that during this phase, the bean is in a usable state, and it can interact with other beans and components.
Destruction Callbacks:

When the application context is closed or the bean is explicitly destroyed (in the case of a prototype-scoped bean), Spring allows for the execution of destruction callbacks. This phase can involve calling methods like destroy (if the bean implements the DisposableBean interface) and any custom destroy-method configured in the bean’s definition. This is where you can perform cleanup tasks like closing resources, releasing database connections, or saving state.
Destruction (for Prototype-Scoped Beans):

In the case of prototype-scoped beans, they are not managed by Spring for destruction. It is the responsibility of the application to handle the destruction of prototype beans explicitly.
Here’s an example of a bean definition in an XML configuration file that includes init-method and destroy-method:

xml
Copy code

<bean>
<!-- Properties and dependencies -->
</bean>

20
Q

@Resource what is this?

A

Description: The @Resource annotation from JSR-250 is used for dependency injection by name. It is applied to fields or setter methods.

@Resource(name = “myMusicRatesFinder”)
public void setMusicRatesFinder(MusicRatesFinder musicRatesFinder) {
this.musicRatesFinder = musicRatesFinder;
}

21
Q

@Value

A

Description: The @Value annotation is used to inject externalized property values into beans. It can inject values from properties files, environment variables, or system properties.

”””
public MusicRatingService(@Value(“${musicMagazine.name}”) String musicMagazineName) {
this.musicMagazineName = musicMagazineName;
}

”””

22
Q

@PostConstruct

A

Description: The @PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization.

”””
@PostConstruct
public void init() {
System.out.println(“Post construct is called”);
}

”””

23
Q

@PreDestroy

A

Description: The @PreDestroy annotation is used on methods as a callback notification to signal that an instance is in the process of being removed by the container.

”””
@PreDestroy
public void destroy() {
System.out.println(“Pre destroy is called”);
}

”””

24
Q

What is the purpose of the @Bean annotation?

A

To indicate that a method instantiates, configures, and initializes a new object to be managed by the Spring IoC container, similar to the <bean></bean> element in XML configuration.

25
Q

What does the @Configuration annotation indicate?

A

It indicates that a class is a source of bean definitions and lets inter-bean dependencies be defined by calling other @Bean methods within the same class.

26
Q

How do you enable component scanning in a @Configuration class?

A

By using the @ComponentScan annotation.

27
Q

What lifecycle annotations are supported by @Bean?

A

@PostConstruct and @PreDestroy from JSR-250, as well as init-method and destroy-method attributes.

28
Q

How do you specify the scope of a bean in a @Bean method?

A

By using the @Scope annotation

29
Q

What is the purpose of the @Import annotation?

A

To load @Bean definitions from another configuration class.

30
Q
A
31
Q

Differences between @Component, @Repository, @Service and @Controller

A

In Spring Framework, @Component, @Repository, @Service, and @Controller are stereotype annotations used to define different types of Spring-managed components. While they are often used interchangeably, they carry specific semantics that hint at the roles these components play within an application:

@Component:

General-purpose stereotype annotation indicating a Spring-managed component.
It is a generic stereotype annotation used for any plain Java class.
It marks the Java class as a Spring component eligible for auto-detection and instantiation by the Spring container.
Typically used for general-purpose beans or components that don’t fit into more specific stereotype categories like @Service, @Repository, or @Controller.
@Repository:

Indicates that a class fulfills the role of a repository or a DAO (Data Access Object).
It’s often used to annotate classes that interact with a database, providing CRUD (Create, Read, Update, Delete) operations or data access functionalities.
Spring provides specific exception translation for classes annotated with @Repository, translating persistence-specific exceptions into Spring’s DataAccessException.
@Service:

Denotes a class that provides some business logic, service, or workflow functionality.
Typically used to annotate classes at the service layer, containing the application’s business logic.
Services are generally transactional and encapsulate the application’s business logic, orchestrating different components to fulfill use cases.
@Controller:

Identifies a class as a controller in the MVC (Model-View-Controller) pattern for web applications.
Used in Spring MVC to define controller classes that handle incoming HTTP requests, interact with models, and return appropriate views or data to the client.
Controllers in Spring MVC manage the application’s flow and handle user interactions.

32
Q

@Required vs @Autowired vs @Qualifier annotations

A

The @Required, @Autowired, and @Qualifier annotations are used in Spring for different purposes related to dependency injection:

@Required:

Indicates that the affected bean property must be populated during configuration. This annotation is more relevant to XML-based configuration rather than annotation-based or Java-based configuration.
If a bean marked with @Required in XML configuration isn’t properly configured with its dependencies, it throws a BeanInitializationException during application startup.
Note: As of Spring 5.1, the @Required annotation is deprecated as other means of marking required dependencies (such as @Autowired(required = true)) provide more flexibility and are more commonly used with annotations and Java-based configurations.
Example:

java
Copy code
public class MyClass {
private SomeDependency dependency;

@Required
public void setDependency(SomeDependency dependency) {
    this.dependency = dependency;
} } @Autowired:

Marks a constructor, a field, a method, or a parameter to be autowired by Spring’s dependency injection mechanism.
When used at the field level, Spring will attempt to automatically wire the dependencies by type. It can be used in combination with @Qualifier to specify which bean should be injected if multiple beans of the same type exist.
It’s a more flexible and commonly used annotation compared to @Required and is widely used with annotation-based and Java-based configurations.
Example:

java
Copy code
public class MyClass {
private SomeDependency dependency;

@Autowired
public MyClass(SomeDependency dependency) {
    this.dependency = dependency;
} } @Qualifier:

Used in combination with @Autowired to specify the particular bean to be injected when multiple beans of the same type exist.
Allows for more fine-grained control over which bean to inject by specifying the bean’s qualifier value (usually the bean’s name or a custom qualifier).
Example:

java
Copy code
public class MyClass {
private SomeDependency dependency;

@Autowired
@Qualifier("specificBean")
public void setDependency(SomeDependency dependency) {
    this.dependency = dependency;
} }
33
Q

@Transactional

A

Imagine you’re transferring money between two bank accounts. A transaction involves debiting money from one account and crediting it to another. Now, consider these key points:

Consistency: Imagine if, during this transfer, the system crashed after deducting money from one account but before adding it to the other. In a non-transactional scenario, you’d lose track of where the money went.

Atomicity: Transactions ensure that all steps in an operation either succeed together or fail together. In the bank transfer example, if something goes wrong (like an error or system crash), the entire transfer is rolled back, so neither account is affected partially.

Isolation: Multiple transactions might be happening simultaneously. Isolation ensures that while one transaction is in progress, others don’t interfere with its data until it’s completed. For the bank transfer, it prevents two different transactions from reading the same data at the same time and causing discrepancies.

Durability: Once a transaction is committed, its changes are permanent, even in the face of system failures. In our example, if the transfer was successful and committed, it stays that way, even if the system crashes after.

In essence, the @Transactional annotation helps ensure data integrity and consistency by bundling operations into a single unit of work. It’s like a protective wrapper around critical operations, ensuring they happen reliably and completely, without leaving data in an inconsistent or erroneous state.

If an exception occurs during the execution of this method, the transaction will be rolled back.

34
Q

What’s new in Spring Framework 5.0?.

A

Support for reactive programming.

35
Q

If we forget to put service annotation on class, will there be an error?

A

Yes, there will be a Runtime error.

36
Q
  1. Have you heard about @Bean can you set it to class?
A

No, it is a method level annotation.

37
Q

Can you make @Bean annotation inside @Component class?

A

Yes. You can.

38
Q

If I have method with @Bean and do not have configuration class. will it work
?

A

Yes. It will work. Even if the @Bean annotated method is defined in a class without any
annotation.

39
Q

How can I make class visible for spring to create a bean for it without
annotating it with @Configuration?

A

Using @Component annotation on the clas

40
Q

How to exclude some packages from componentscan ?

A

@ComponentScan(basePackages = “”,
includeFilters = @Filter(type=FilterType.REGEX, pattern=”com.package”,
excludeFilters=@Filter(type=FilterType.ASSIGNABLE_TYPE, classes =..class)

41
Q

What about internationalization. Which one supports it: BeanFactory or
ApplicationContext ?

A

ApplicationContext supports internationalization.

42
Q

In which case the transaction will be rolled back?

A

If Runtime exception happens it will be rolled back.

43
Q

IF we want to use @Transactional with methods, they must be public and
must be called from outside the class. Why? What Spring does when we
mark the method as transactional.

A

In this case, spring creates proxy. In proxy mode, only external method calls coming in
through the proxy will be intercepted. Protected or private methods will not be
intercepted.

44
Q

If I have two methods, both having transactional annotations, how many
transaction happens?

A

Only one.

45
Q

Is it possible to create custom scope?

A

It is possible, by implementing Scope interface. We must also ensure that the
implementation is thread-safe.