Spring Flashcards

1
Q

spring framework

A

opensource java application framework which uses two principles, dependecy injection and inversion of control

Spring is not one big framework. It is broken down into modules. This can be seen in the Maven Dependencies folder, where there are a lot of JAR files instead of just one big JAR.

This enables some modules to be used without using the whole framework

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

inversion of control

A

Traditionally, the class which needed the dependency created an instance of the dependency. The class decided when to create the dependency and how to create it.

Spring takes this responsibility from the class and creates the object itself. The developer simply mentions the dependency and the framework takes care of the rest.

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

dependency injection

A

It is the process by which Spring looks up the beans that are needed for a particular bean to function and injects them as a dependency.

Spring can perform dependency injection by using constructor or by using a setter method.

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

IOC Container

A

is a framework that provides the Inversion of Control functionality.
Spring offers two implementations of IOC container

Bean factory - legacy IoC container and provides basic management for beans and wiring of dependencies.

Application context - It includes basic management of beans and wiring of dependencies as provided by the bean factory. Additional features in application context include Spring AOP features, internationalization, web application context, etc.

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

Modules of spring architecture

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

Autowiring approaches

A

in order:
qualifier - if i specify the name in qualifier, then that bean will be selected
primary - if primary is present, then if no qualifier is given, it will take the primary bean
name

@Primary annotation should be used if there is one clear favorite to be used in a majority of situations. In some cases, one algorithm might be more efficient or more important than the rest and is declared as the primary choice. The bean with @Primary gets chosen unless another bean is required, which can be specified with @Qualifier. The bean with @Qualifier is only used to request an alternate bean in case the primary choice is not required.

@Autowired annotation resolves dependencies by type. If there are more than one beans of the same type, a conflict arises. We have seen three different approaches to resolve conflicts. They can be resolved using the @Primary annotation, renaming the variable to match the name of the class, or by using the @Qualifier annotation.

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

Bean scopes

A

There are six types of scopes: singleton, prototype, request, session, application, and websocket.

Relevant Scopes for REST API Development
Singleton Scope
Prototype Scope
Request Scope
Session Scope

. Singleton Scope
@Service
Description: A single instance of the bean is created and shared across the entire Spring container. This is the default scope in Spring.
Use Case: Typically used for stateless services, configuration classes, and beans that are shared across the application.
Relevance: Highly relevant for REST API development as many services and repositories are designed to be stateless and shared.

  1. Prototype Scope
    @Scope(“prototype”)
    @Component
    Description: A new instance of the bean is created each time it is requested from the Spring container.
    Use Case: Used for stateful beans or beans that hold transient data.
    Relevance: Less common in REST API development but useful when you need a new instance for each request or operation
  2. Request Scope
    @Scope(“request”)
    @Component
    Description: A new instance of the bean is created for each HTTP request. It is destroyed once the request is completed.
    Use Case: Used for beans that need to be aware of and tied to the lifecycle of an HTTP request.
    Relevance: Very relevant for REST API development, especially for components like request-scoped services or filters that need to process data specific to a single HTTP request.
  3. Session Scope
    @Scope(“session”)
    @Component
    Description: A new instance of the bean is created for each HTTP session. It is destroyed when the session is invalidated.
    Use Case: Used for beans that need to maintain state across multiple requests within the same HTTP session.
    Relevance: Useful for REST APIs that need to manage user sessions, such as authentication and user session data.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Spring vs. Gang of Four singleton#

A

in Spring it means one bean per application context. By the GoF definition, even if there were more than one application contexts running on the same JVM, there would still be only one instance of the singleton class.

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

SINGLETON VS PROTYPE BEAN SCOPE

A

Spring creates a singleton bean even before we ask for it while a prototype bean is not created till we request Spring for the bean

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

what happens if i inject prototype bean into singleton bean ( means dependent of singleton is a prototype)

A

The prototype bean is injected into the singleton bean at the time of creation of the singleton bean when the container initializes it.

When a prototype bean is injected into a singleton bean, it loses its prototype behavior and acts as a singleton.

we can use proxymode to overcome this behaviour
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode=ScopedProxyMode.TARGET_CLASS)

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

what is the use of @ComponentScan

A

@ComponentScan(basePackages={“io.datajek.spring.basics.movierecommendersystem.lesson9”,
“io.datajek.spring.basics.movierecommendersystem.lesson10”})

Spring will look for beans in the packages specified

we can also specify filter to further refine the scan
FilterType.ANNOTATION
FilterType.ASPECTJ
FilterType.ASSIGNABLE_TYPE
FilterType.REGEX
FilterType.CUSTOM
eg:@ComponentScan(basePackages = “io.datajek.spring.basics.movierecommendersystem.lesson10”)
@ComponentScan(includeFilters = @ComponentScan.Filter (
type= FilterType.REGEX,
pattern=”io.datajek.spring.basics.movierecommendersystem.lesson9.*”))

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

check if a package contains bean

A

appContext.containsBean(“collaborativeFilter”)

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

@preDestroy

A

The method having this annotation is called when the bean is in the process of being removed from the container. All cleanup stuff can be performed in this method. A method with the @PreDestroy annotation can be used to release resources or close a database connection.

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

@postConstruct

A

If the developer wants to perform a task after the dependencies have been populated, it can be done by calling a method annotated with the @PostConstruct annotation.

The method can have any name and its return type is always void. After the bean is created, we can initialize the contents of the bean, load data, establish a database connection, or connect to a web server. The post construct method is only called after all the dependencies have been populated.

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

CDI Annotations

A

It is the Java EE standard. if the application is migrated to another framework, the cdi annotatons are valid intead of the spring specific annotations.

@Named can be used instead of @Component
@Inject instead of @Autowired

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

lifecycle of prototype beans

A

Spring manages the entire lifecycle of singleton beans but it does not completely manage the lifecycle of prototype beans. This is because there might be a large number of prototype instances and the container can become overwhelmed keeping track of them.

it is the responsibility of the application to destroy the bean and free up any resources that it has acquired.

15
Q

application properties file
@Value
@PropertySource

A

Applications have a lot of configuration and keeping it separate from the code leads to clarity. If the property file is inside the jar when the application is built, it can’t be changed later without having to un-compress the jar.

The application-properties file is a text file that defines the key-value pair for a property
in app.properties file : recommender.implementation.favoriteMovie = Finding Dory
in the class, use anotation above the variable
@Value(“${recommender.implementation.favoriteMovie}”)
String favoriteMovie;

now in main class, we will point to the name of the properties file like this:
@PropertySource(“classpath:app.properties”)

16
Q

xml configuration file appContext.xml

A

meta data for validating the tags:

<beans>

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

bean definitions eg:

<bean>
</bean>

<bean>
</bean>

The IOC container will read the appContext.xml file and create objects of the classes mentioned in it. It will call the constructor of the class to create the object by giving it the name that we specified as the id

now to create application context, we use the below:
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(“appContext.xml”);

to the beans present once the appcontxt is loaded, use below:
Arrays.toString(appContext.getBeanDefinitionNames())

17
Q

dependency injection in xml config

A

In XML, a dependency can be defined in multiple ways:
1)using <property> tag => setter injection. a no arg constructor or default constructor is needed
2)using constructor injection</property>

1)<bean></bean>

<property></property>

</bean>

2)<bean></bean>

<constructor-arg></constructor-arg>

</bean>

18
Q

<context:annotation-config> and <context:component-scan>
</context:component-scan></context:annotation-config>

A

<context:annotation-config> tag is redundant in the presence of <context:component-scan> tag as the latter can detect both bean and dependency injection annotations.
</context:component-scan></context:annotation-config>

19
Q

service, controller, repository annotations. - stereotype annotations

A

@Controller is used to define a controller in the web layer. Spring scans a class with @Controller to find methods that are mapped to different HTTP requests. It makes sure that the right view is rendered to the user. @RestController is a specialized form of @Controller.

We can replace the @Component annotation with stereotype annotations. Instead of @Component, we can use the @Service annotation for classes with business logic

we can replace the @Component annotation with @Repository annotation if it belongs to the data access layer.

20
Q

@RestController

A

@RestController is a specialized form of @Controller annotation which handles REST requests and responses. It automatically handles conversion to JSON.

21
Q

devtools dependency

A

Automatic restart of the application is an important feature of devtools. Whenever any change is made to the code, devtools causes an automatic restart when a file on its classpath changes. Spring Boot provides two classloaders: one for the classes that do not change like third-party jars and the other for application code using the RestartClassLoader. When the code is changed, only the RestartClassLoader is loaded, which causes the restart to be much faster.

22
Q

when do you need custom row mapper

A

1) when the naming conventions in db is aligning with the bean naming standards due to legacy systems, third party applications tc

23
Q

JPA

A

JPA challenges the notion of writing queries and mapping the data back.
Using JPA, we can map a Java class or bean to a table. The members of the class map columns in the table.

JPA under ORM layer
JPA creates a schema based on the entities and defines relationships between entities. The Object-Relational Mapping (ORM) layer maps the objects to a database table.

JPA is a standard of Object Relational Mapping
Hibernate, the most popular ORM framework prompted the creation of the JPA standard

The benefit of using JPA instead of Hibernate is that JPA is a standard and one can switch to any other implementation later.

24
Q

JPA Annotations

A

1)@Entity annotation to map this class to the table
@Entity
Public class Player {
}

2) @Table annotation if table name and class name is different. this will map to table name.
@Table(name=”Player”)

3)@Id annotation is used to indicate the primary key

4)@GeneratedValue annotation will automatically generate Id values.

@Entity
public class Player {
@Id
@GeneratedValue
private int id;
}

5)@Column annotation mentions the name of the column that matches an attribute of the class. This is used when column name dont match with the field value in the class

The Player class now has three constructors; a no-arg constructor, one that initializes all five attributes, and one that initializes all attributes except the primary key.

25
Q

jackson integration in spring REST

A

Spring also automatically handles Jackson integration which makes conversion of data from JSON to POJO and vice versa a breeze. Any JSON data received by the controller is automatically converted to a POJO and any POJO returned by the controller is converted to JSON. === this process is called data binding

Jackson handles the conversion between JSON and POJOs by making use of the getter and setter methods of a class. To convert a JSON object to POJO, the setter methods are called. Vice versa, to create a JSON object from a POJO, the getters methods are used. Jackson has access to the getters and setters only, not the private fields of the class.

26
Q

What is REST

A

Representational state transfer
client and server are not dependent on each other, language independednt

The REST architecture is stateless meaning that the client only manages the session state and the server only manages the resource state.

Without Statelessness (Stateful Example):

Client Login:

The client logs in, and the server creates a session, storing the session state (like user details, session ID).
The server maintains the session state across multiple requests.
Subsequent requests from the client are linked to this session.
Request Handling:

The client sends a request without complete state information, relying on the server to remember the session state.
The server uses the stored session state to process the request.
With Statelessness (RESTful Stateless Example):

Client Login:

The client logs in and receives an authentication token (like JWT).
The client stores the token and sends it with every subsequent request.
Request Handling:

The client sends a request with the complete state information (e.g., the authentication token).
The server validates the token and processes the request without needing to remember any previous state.

27
Q
A