Spring-boot

Index

  1. Versions
  2. Interview Questions

Versions

VersionRelease DateMajor FeaturesComment
3.2.3February 22, 2024Upgraded dependencies (Spring Framework 6.1.4, Spring Data JPA 3.1.3, Spring Security 6.2.2, etc.) https://www.codejava.net/spring-boot-tutorials
3.1.3September 20, 2023Enhanced developer experience, improved reactive support, and updated dependencies https://spring.io/blog/2022/05/24/preparing-for-spring-boot-3-0
3.0.xMay 2020 – December 2022Introduced reactive programming, improved build system, and various dependency updates throughout the series (refer to official documentation for details)
2.xMarch 2018 – May 2020Introduced Spring Boot actuator, developer tools, and auto-configuration (refer to official documentation for specific features within each version)2.7.7 used in project (switch)
1.xApril 2014 – February 2018Initial versions focusing on simplifying Spring application development1.5.22.RELEASE used in project (consumers)

Springboot versions and corresponding spring version support:

Spring Boot VersionSupported Spring Framework Versions
1.x4.x
2.0.x – 2.3.x5.x
2.4.x5.x, 6.x
3.0.x – 3.2.x6.x


Interview Questions

  • Why springboot over spring?
    1. Convention-over-Configuration:
      • Spring Boot: Spring Boot follows convention-over-configuration principles, reducing the need for explicit configuration. Annotations like @Service are automatically recognized and configured based on conventions.
      • Spring (Traditional): In traditional Spring applications, while you can use annotations, you might need more explicit configuration, especially in XML-based configurations.
    2. Auto-Configuration:
      • Spring Boot: Spring Boot provides auto-configuration, which means that common configurations are automatically applied based on the project’s dependencies. For example, if you have @Service annotated classes, Spring Boot will automatically configure them as Spring beans.
      • Spring (Traditional): In traditional Spring, you might need to configure components more explicitly, specifying details in XML files or Java-based configuration classes.
    3. Reduced Boilerplate Code:
      • Spring Boot: Spring Boot’s defaults and starters significantly reduce boilerplate code. You can focus more on writing business logic and less on configuration.
      • Spring (Traditional): Without the conventions and defaults of Spring Boot, you might find yourself writing more configuration code to set up beans and application context.
    4. Simplified Dependency Management:
      • Spring Boot: The use of starters simplifies dependency management. With the appropriate starter, you get a predefined set of dependencies, including those for services, making it easy to include and manage dependencies.
      • Spring (Traditional): While you can manage dependencies in traditional Spring, Spring Boot provides a more streamlined way to do so with starters.
    5. Out-of-the-Box Features:
      • Spring Boot: Spring Boot provides out-of-the-box features, such as embedded servers, metrics, and health checks. These features are often automatically configured, making it easier to develop production-ready applications.
      • Spring (Traditional): While you can manually configure these features in traditional Spring, Spring Boot simplifies the process and encourages best practices.
    6. Faster Project Bootstrap:
      • Spring Boot: With its starters and defaults, Spring Boot allows for faster project bootstrapping. You can create a fully functional application with minimal setup.
      • Spring (Traditional): Setting up a traditional Spring application might involve more manual configuration and a longer setup time.
  1. Annotations in springboot
    • @SpringbootApplication
      1. @EnableAutoconfiguration
      2. @ComponentScan
      3. @SpringBootConfiguration specialised form of @Configuration

Junit and Mocking and spy

Index

  • Junit
  • Mockito
  • testing private method (reflection ,powermock)

2 testing fameworks- MOckito abd Sping testing

MOckMOckBean
annotationpary of MockitoframeworkSPring testing framework
framework@RunWith(MockitoJUnitRunner.class) public class MyServiceTest { @Mock private MyRepository myRepository;@SpringBootTest public class MyServiceIntegrationTest { @Autowired private MyService myService; @MockBean private MyRepository myRepository;
PurposeUnitTetsingIntegration testing

Spy vs Mock

@spy@Mock
Functionalitypartially mocked version of a real object.complete replacement for a real object.
CreationWraps an existing objectCreates a new object
ControlPartial control (can define specific behaviors for specific methods)Full control over behavior
Use caseTesting interactions within a real object with some real behaviorIsolating dependencies, unit testing with specific behavior
accesscan access private methods of the original objectcannot access private methods of the original object
examplebelow codebelow code //

Mock usage

// Interface we want to test
public interface EmailService {
  void sendEmail(String recipient, String message);
}

// Test class using mock
@Test
public void testSendEmail() {
  // Create a mock object of EmailService
  EmailService mockEmailService = Mockito.mock(EmailService.class);

  // Define behavior for the mock object
  Mockito.when(mockEmailService.sendEmail("user@example.com", "Hello world!")).thenReturn(true);

  // Use the mock object in your test logic
  myService.sendNotification(mockEmailService, "user@example.com", "Hello world!");

  // Verify interactions with the mock object
  Mockito.verify(mockEmailService).sendEmail("user@example.com", "Hello world!");
}

IN above example :

  • We create a mock object of EmailService using Mockito.mock.
  • We define behavior for the sendEmail method using Mockito.when. Here, it always returns true.
  • We use the mock object in the test and verify its interaction later.

Spy usage

// Real implementation of EmailService
public class RealEmailService implements EmailService {
  @Override
  public void sendEmail(String recipient, String message) {
    // Send email logic goes here (not shown for simplicity)
  }
}

// Test class using spy
@Test
public void testSendEmailWithSpy() {
  // Create a real object
  EmailService realEmailService = new RealEmailService();

  // Create a spy object from the real object
  EmailService spyEmailService = Mockito.spy(realEmailService);

  // Define behavior for specific method (optional)
  Mockito.when(spyEmailService.sendEmail("admin@example.com", "Alert!")).thenReturn("Sent successfully");

  // Use the spy object in your test logic
  myService.sendNotification(spyEmailService, "user@example.com", "Hello world!");
  myService.sendNotification(spyEmailService, "admin@example.com", "Alert!");

  // Verify interactions (optional)
  Mockito.verify(spyEmailService, times(2)).sendEmail(anyString(), anyString());
}

IN above example :

  • Create a real RealEmailService object.
  • Create a spy of the RealEmailService using Mockito.spy.
  • Define behavior for the sendEmail method to return a specific message for “admin@example.com” email.
  • Use the spy object and verify interactions (optional).

		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-module-junit4</artifactId>
			<version>1.7.4</version>
		</dependency>

https://www.learnbestcoding.com/post/21/unit-test-private-methods-and-classes

REfernce

https://www.tutorialspoint.com/mockito/mockito_spying.htm

Spring Interview Questions

Index

  1. Spring bean scope
  2. Use of @qualifer and @primary 
  3. Security in spring 
  4. Dependency injection 
  5. Rest controller 
  6.  Difference between DI and IOC 
  7.  Bean lifecycle 
  8. Req attr Param 
  9. Spring JDBC 
  10.  Qualifier 
  11. Exception Handler 
  12. diff @Configuration @EnableAutoConfiguration & @ComponentScan 
  13. Circular Dependency (How to resolve)
  14. Proxy and why needed? how to create one?


Spring bean scope 

Thymeleaf

Contents

  1. Introduction
    1. Content Organisation
    2. Flow of control
  2. Brief-on-usage
    1. Dependencies
    2. Defining Layout page
    3. Defining content page
    4. Using script in layout-Content page
  3. Resources and references

Contents can be organised on UI as:

  • master-page[layman term] orLayout page[thyme-leaf specific term] which loads other pages on it (header/Footer)
  • Content page

Flow of control

  • Sprinboot(once added with thymeleaf dependecy) looks for src/main/resources/template folder for UI pages
  • the template or the view pages (basically html files in template folder) interact with Controller
  • Use Model to return data to view and in the return statement put the name of view/template to return to.
  • One thing to note about template is that it’s a normal html file but has a extra attribute specific to thyme-leaf to support it’s features. refer below for syntax

Dependencies-

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
    <version>2.5.1</version>
</dependency>




Defining Layout Page

The layout page is similar to any other HTML page. However, you must add the xmlns:layout attribute to the  html tag.

<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

Next, you need to specify the part of the layout page where you want the content to appear. This is done using a div tag with the fragment attribute. So anything outside this div tag would remain fixed while the content of the div tag would be changing. The code below shows how you do this.

<div layout:fragment="content">
    <p>Changing contents</p>
</div>

Defining Content Page

Just like in the layout page, you need to add the xmlns:layout attribute. But additionally, you also must add the layout: decorate attribute as well. The layout:decorate attribute would have a value set to the layout page(without the .html extension).  This is shown below:

<html lang="en" 
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="_layout">

Here, the layout page is _layout.html placed inside the templates folder.

Having added this HTML markup, you then need to specify the div tag that would wrap the whole content of the page. This is done as shown below:

<div layout:fragment="content">

<!--Content of the page-->

</div>

At this point, anything you want in the content page must be inside this div tag include modals.

4. Using Scripts in Layout-Content Page [Confusing – need to see reference resources]

First, note that scripts defined in the layout page, apply to both the layout and the content page. However, you may want a script that applies only to the layout page. This is achieved using the th:block tag.

For instance, we want a script called account.js to execute only for the content page. Then take the steps below:

In the layout page, add the following block,

<th:block layout:fragment="script"></th:block>

In the content page, add

<th:block layout:fragment="script">
    <script th:src="@{/js/accounts.js}"></script>
</th:block>

In this case, the accounts.js script is placed inside the js folder in the static folder.