Spring Framework Notes
Published: 2023-04-01 09:56:27

1) Difference b/w Spring and Spring Boot
Spring is an application framework for developing java based applications.
Spring Boot is Spring's convention-over-configuration solution for creating stand-alone, Spring-based Applications. It is preconfigured with the Spring team's "opinionated view" of the best configuration and use of the Spring platform and third-party libraries.

2) Spring auto-configuration is disabled by default and you need to use either @SpringBootApplication or @EnableAutoConfiguration annotations on the Main class to enable the auto-configuration feature.
The @EnableAutoConfiguration is used to enable auto-configuration but @SpringBootApplication is a combination of @Configuration, @EnableAutoConfiguration and @ComponentScan annotations to enable Java-based configuration and component scanning in your project.

3)What embedded containers does Spring Boot support?
Spring Boot support three embedded containers: Tomcat, Jetty, and Undertow.
By default, it uses Tomcat as embedded containers but you can change it to Jetty or Undertow.


4) What is the difference between @Autowired vs @Inject Annotation?
@Inject is a standard annotation (JSR-330) for dependency injection and @Autowired is Spring framework specific.

5) Google Guice another example of DI framework.

6) What is the difference between a singleton and prototype bean?
There is an attribute in bean tag named 'singleton' if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default, it is set to true. So, all the beans in spring framework are by default singleton beans.
Singleton: means single bean definition to a single object instance per Spring IOC container.
Prototype: means a single bean definition to any number of object instances.

7) Difference between @Component, @Service, @Controller, and @Repositoring annotation in Spring MVC?
From Spring 2.5 annotation-based dependency injection was introduced, which automatically scans and register classes as Spring bean which is annotated using @Component annotation.
This means you don't declare that bean using the <bean> tag and inject the dependency, it will be done automatically by Spring. This functionality was enabled and disabled using <context:component-scan> tag.
@Service, @Controller, and @Repository annotation are nothing but the specialized form of @Component annotation for certain situations.
@Component and @Controller are same with respect to bean creation and dependency injection but later is a specialized form of former. For example, DispatcherServlet will look for @RequestMapping on classes which are annotated using @Controller but not with @Component.
Same is true for @Service and @Repository annotation, they are a specialization of @Component in service and persistence layer. A Spring bean in the service layer should be annotated using @Service instead of @Component annotation and a spring bean in the persistence layer should be annotated with @Repository annotation.

8) Below are some Java connection pooling libraries:
C3PO
Apache DBCP2
tomcat-jdbc
HikariCP
vibur
BoneCP

9) The purpose of an IoC container is to manage dependencies between objects.
10) Auto-wiring is a slow but it reduces the need for writing a lot of XML.

11) Differences between @RequestParam and @PathVariable annotations in Spring MVC?
@RequestParam is used to get the request parameters from URL, also known as query parameters, while @PathVariable extracts values from URI.
For example, if the incoming HTTP request to retrieve a book on topic "Java" is http://localhost:8080/shop/order/1001/receipts?date=12-05-2017, then you can use the @RequestParam annotation to retrieve the query parameter date and you can use @PathVariable to extract the orderId i.e. "1001" as shown below:

@RequestMapping(value="/order/{orderId}/receipts", method = RequestMethod.GET)
public List listUsersInvoices(                               @PathVariable("orderId") int order,
 @RequestParam(value = "date", required = false) Date dateOrNull) {
...
}

The required=false denotes that the query parameter can be optional, but the URL must have the same URI.

12) How to deal with cyclic dependency in spring config xml?
Circular dependencies is the scenario when two or more beans try to inject each other via constructor. When having a circular dependency, Spring cannot decide which of the beans should be created first, since they depend on one another. In these cases, Spring will raise a BeanCurrentlyInCreationException while loading context.
Circular dependency can happen in Spring when using constructor injection; if you use other types of injections you should not find this problem since the dependencies will be injected when they are needed and not on the context loading.
a) By using setter injection.
b) By using @Lazy at constructor injection point.
https://www.baeldung.com/circular-dependencies-in-spring

13) Spring Boot configures Hibernate as the default JPA provider.

14) In Spring Boot 1, the default connection pool was Tomcat, but with Spring Boot 2 it has been changed to HikariCP.

15) The Spring team advocates test-driven development (TDD).

16) Annotation injection is performed before XML injection. So XML injection overrides.

17) The beans in spring container can be created in five scopes i.e. singleton, prototype, request, session and global-session.

Singleton - Only one instance of bean per spring container (Default)
Prototype - A new instance every time bean is requested
Request - Single bean instance per HTTP request
Session - Single bean instance per HTTP session
Global Session - Single bean instance per global HTTP session

The three bean scopes (request, session and global-session) are web applications related. Essentially these are available through web aware application context (e.g. WebApplicationContext). Global-session is a little different in sense that it is used when application is portlet based. In portlets, there will be many applications inside a big application and a bean with scope of ‘global-session’ will have only one instance for a global user session.

global-session is something which is connected to Portlet applications. When your application works in Portlet container it is built of some amount of portlets. Each portlet has its own session, but if your want to store variables global for all portlets in your application than you should store them in global-session. This scope doesn’t have any special effect different from sessionscope in Servlet based applications.

18) Usually when we build multi-tier applications we don’t want to clutter all the beans in one config file [appname]-servlet.xml. For example if you configure spring security you wanted to include all those beans in security-context.xml, in the same way all the beans belonging to service layer are configured in applicationContext.xml and some would like to configure beans belonging to DAO layer in dao-context.xml. So when you configure all these beans in different context files, you need to let know spring that these files exist as spring only knows about [appname]-servlet.xml. ContextLoaderListener will help spring recognize all the other context files.

19) ApplicationContext:
a) The ApplicationContext is where your Spring beans live
b) applicationContext.xml is the root context configuration for every web application
c) Spring loads applicationContext.xml file and creates the ApplicationContext for the whole application
d) There will be only one application context per web application
e) If you are not explicitly declaring the context configuration file name in web.xml using the contextConfigLocation param, Spring will search for the applicationContext.xml under WEB-INF folder and throw FileNotFoundException if it could not find this file
f) Application-Contexts are hierarchial and so are WebApplicationContexts.

20) How do you control the concurrent Active session using Spring Security?
One can configure the session control by creating two beans bean of types SessionRegisteryImpl and ConcurrentSessionControlAuthenticationStrategy respectively; and setting the maximum number of sessions to 3 and the parameter exceptionIfMaximumExceeded value to true. So if a user authenticates more than three times he will be rejected.

21) Limitations of default implementation of concurrent session control:
a) The default implementation of SessionRegistery uses volatile storage because it stores the session information in the memory. The code below shows a part of the class implementation where we can see that the session information is stored in a ConcurrentMap. So if the server restarts that information will be lost and the user can authenticate again even if he exceeds the session limit.
b) Another limitation is related to the use of the default implementation in a cluster. Since there is no synchronization between the different cluster nodes, each node will manager the concurrent sessions separately.  So the users can be authenticated in each node until reaching the limit.


**References/Attributions:**
https://www.javaspringclub.com/important-notes-on-spring-framework/
https://dzone.com/articles/how-spring-security-concurrent-session-control-wor
https://unsplash.com/photos/koy6FlCCy5s