0% found this document useful (0 votes)
8 views

SpringAndSpringBootinterviewqsns

The document provides an overview of various Spring Boot features and annotations, including @SpringBootApplication, @RestController, and @ControllerAdvice, explaining their roles and configurations. It discusses dependency injection, bean scopes, caching, and error handling, as well as how to set up Spring Boot applications and integrate them with databases. Additionally, it covers advanced topics like Spring Boot Actuator, asynchronous calls, and security configurations.

Uploaded by

ANKIT MATHUR
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

SpringAndSpringBootinterviewqsns

The document provides an overview of various Spring Boot features and annotations, including @SpringBootApplication, @RestController, and @ControllerAdvice, explaining their roles and configurations. It discusses dependency injection, bean scopes, caching, and error handling, as well as how to set up Spring Boot applications and integrate them with databases. Additionally, it covers advanced topics like Spring Boot Actuator, asynchronous calls, and security configurations.

Uploaded by

ANKIT MATHUR
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 8

1)The @SpringBootApplication annotation is equivalent to using @Configuration,

@EnableAutoConfiguration, and @ComponentScan with their default attributes

2)@RestController:@Controller and @ResponseBody

->It depends on what you use for the remainder of the framework. In theory nothing
changes as the @Service and @Repository annotations are basically @Component
annotations. The same could be said for @Controller or @Endpoint (for Spring Ws and
there are more).

However they express an intent of what a class is (a service, a repository) and


makes it clear to the user to what layer that class belongs.

->@PropertySource,@Value("${demo.item-price}"), application.properties,
application-{profile}.properties,spring.profiles.active

->java -jar app.jar


--spring.config.location=file:///Users/home/config/jdbc.properties

->https://www.baeldung.com/circular-dependencies-in-spring

->Spring Profiles provide a way to segregate parts of your application


configuration and make it be available only in certain environments. Any
@Component, @Configuration or @ConfigurationProperties can be marked with @Profile
to limit when it is loaded, as shown in the following example:

@Configuration(proxyBeanMethods = false)
@Profile("production")
public class ProductionConfiguration {

// ...

#@ControllerAdvice
->@ControllerAdvice is very useful to handle exceptions when you have multiple
Spring REST API controllers doing a lot of different work.

That means when writing any application you encounter exceptions and to handle them
at each method level is tedious and not optimal. So in order to overcome that,
spring has introduced the concept of @ControllerAdvice which will intercept all the
controllers and look for the exceptions thrown. This is at a global level means you
only have one @ControllerAdvice for each application and it will intercept the
exceptions thrown by the controllers in that particular application context.
->https://medium.com/@jovannypcg/understanding-springs-controlleradvice-
cd96a364033f

->By default, SpringApplication converts any command line option arguments (that
is, arguments starting with --, such as --server.port=9000) to a property and adds
them to the Spring Environment. As mentioned previously, command line properties
always take precedence over file-based property sources.

If you do not want command line properties to be added to the Environment, you can
disable them by using SpringApplication.setAddCommandLineProperties(false)

3)@Qualifier, @Primary
->So you can find both @Qualifier and @Primary are telling Spring to use the
specific bean when multiple candidates are qualified to autowire. But @Qualifier is
more specific and has high priority. So when both @Qualifier and @Primary are
found, @Primary will be ignored.
->@Primary means default implementation, while @Qualifier is the specific
implementation.

# @RequestBody annotation maps the HttpRequest body to a transfer or domain object,


enabling automatic deserialization of the inbound HttpRequest body onto a Java
object.

# Spring Boot auto-configures the cache infrastructure as long as caching support


is enabled by using the @EnableCaching annotation.
@Component
public class MyMathService {

@Cacheable("piDecimals")
public int computePiDecimal(int precision) {
...
}

#https://loadninja.com/articles/optimize-api-performance/

#Read filter in springboot for incoming request.

->https://www.baeldung.com/hibernate-one-to-many
->https://www.baeldung.com/jpa-one-to-one

#RestTemplate
->As of Spring Framework 5, alongside the WebFlux stack, Spring introduced a new
HTTP client called WebClient.
WebClient is a modern, alternative HTTP client to RestTemplate. Not only does it
provide a traditional synchronous API, but it also supports an efficient
nonblocking and asynchronous approach.
->RestTemplate’ is a synchronous REST client provided by the core Spring Framework.
->https://www.geeksforgeeks.org/spring-resttemplate/
->https://www.baeldung.com/rest-template

#CORS,CSRF
->https://www.baeldung.com/spring-cors
->https://www.baeldung.com/spring-security-csrf#:~:text=If%20our%20stateless%20API
%20uses,as%20we'll%20see%20next.

3)The BeanFactory is the actual container which instantiates, configures, and


manages a number of beans. These beans typically collaborate with one another, and
thus have dependencies between themselves.

#What is dependency Injection


The process of injecting dependent bean objects into target bean objects is called
dependency injection.

The IoC container creates an object of the specified class and also injects all the
dependency objects through a constructor, a property or a method at run time and
disposes it at the appropriate time. This is done so that we don't have to create
and manage objects manually.

The Spring Framework comes with two IOC containers – BeanFactory and
ApplicationContext. The BeanFactory is the most basic version of IOC containers,
and the ApplicationContext extends the features of BeanFactory.
#https://www.baeldung.com/spring-boot-war-tomcat-deploy
1)extends our main class to SpringBootServletInitializer.
2)Overriding configure method
3)Configure Packaging to WAR

->@SpringBootApplication
public class SpringBootTomcatApplication extends SpringBootServletInitializer {

public static void main(String[] args) {


SpringApplication.run(Application.class, args);
}

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
}

-><packaging>war</packaging>

#CommandLineRunner is a simple Spring Boot interface with a run method. Spring Boot
will automatically call the run method of all beans implementing this interface
after the application context has been loaded.Note that the run method is called
after the application context is loaded, but before the execution of the main
method is complete.
https://www.baeldung.com/spring-boot-console-app

Spring Boot Actuator is a sub-project of the Spring Boot Framework. It includes a


number of additional features that help us to monitor and manage the Spring Boot
application. It contains the actuator endpoints (the place where the resources
live). We can use HTTP and JMX endpoints to manage and monitor the Spring Boot
application. If we want to get production-ready features in an application, we
should use the Spring Boot actuator.
/endpoint/actuator/health

How to run SpringBoot application using commandline

#ehcache
->@EnableCaching
->
@Service
public class PostService {
@Cacheable("posts")
public Post findById(Integer postId) {
System.out.println("Fetching Post");
return new Post(postId, "Demo post");
}

@CachePut("posts")
public void updatePost(Post post) {
// update post
}
@CacheEvict("posts")
public void deleteById(Integer postId) {
// delete post
}
}

->https://www.geeksforgeeks.org/spring-boot-ehcaching/
->https://www.baeldung.com/spring-boot-ehcache

#refresh in SpringBoot actuator


->A simple way to refresh configuration property is to use /refresh endpoint
provided by spring boot actuator

What are the bean scopes available in Spring?


The Spring Framework has five scope supports. They are:

Singleton: The scope of bean definition while using this would be a single instance
per IoC container.
Prototype: Here, the scope for a single bean definition can be any number of object
instances.
Request: The scope of the bean definition is an HTTP request.
Session: Here, the scope of the bean definition is HTTP-session.
Global-session: The scope of the bean definition here is a Global HTTP session.
Note: The last three scopes are available only if the users use web-aware
ApplicationContext containers.

#https://www.javatpoint.com/spring-boot-jpa

#How to connect Spring Boot application to database using JDBC


@Autowired
JdbcTemplate jdbcTemplate;

#How does a spring boot application get started


@SpringBootApplication
public class MyApplication {

public static void main(String[] args) {

SpringApplication.run(MyApplication.class);
// other statements
}
}

#http://localhost:8080/ex/bars?id=100
here id is RequestParam

@RequestMapping(value = "/ex/bars", method = GET)


@ResponseBody
public String getBarBySimplePathWithRequestParam(
@RequestParam("id") long id) {
return "Get a specific Bar with id=" + id;
}

#http://localhost:8080/ex/foos/1
here 1 is PathVariable
@RequestMapping(value = "/ex/foos/{id}", method = GET)
@ResponseBody
public String getFoosBySimplePathWithPathVariable(
@PathVariable String id) {
return "Get a specific Foo with id=" + id;
}

#https://www.baeldung.com/spring-requestmapping
refer this for understanding requestmapping

#PostMapping
@PostMapping("/employees")
public Employee createEmployee(@Valid @RequestBody Employee employee) {
return employeeRepository.save(employee);
}

#PutMapping
@PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable(value = "id") Long
employeeId,
@Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this
id :: " + employeeId));

employee.setEmailId(employeeDetails.getEmailId());
employee.setLastName(employeeDetails.getLastName());
employee.setFirstName(employeeDetails.getFirstName());
final Employee updatedEmployee = employeeRepository.save(employee);
return ResponseEntity.ok(updatedEmployee);
}

Spring Boor retry


#https://bootcamptoprod.com/spring-boot-retry/#:~:text=Spring%20Boot%20Retry%20is
%20a,a%20maximum%20number%20of%20attempts.

@EnableRetry
@SpringBootApplication
public class SpringBootRetryApplication {

public static void main(String[] args) {


SpringApplication.run(SpringBootRetryApplication.class, args);
}

@Retryable(
retryFor = {HttpServerErrorException.class,
HttpClientErrorException.class, ResourceAccessException.class},
maxAttempts = 3,
backoff = @Backoff(delay = 5000))
public Movie getMovieDetails(String movieId) throws ResourceAccessException {
Movie movie = null;
try {
movie = movieApiClient.getMovieDetails(movieId);
} catch (HttpServerErrorException httpServerErrorException) {
System.out.println("Received HTTP server error exception while fetching
the movie details. Error Message: " + httpServerErrorException.getMessage());
throw httpServerErrorException;
} catch (HttpClientErrorException httpClientErrorException) {
System.out.println("Received HTTP client error exception while fetching
the movie details. Error Message: " + httpClientErrorException.getMessage());
throw httpClientErrorException;
} catch (ResourceAccessException resourceAccessException) {
System.out.println("Received Resource Access exception while fetching
the movie details.");
throw resourceAccessException;
}
return movie;
}

@Recover
public Movie recoverMovieDetails(RestClientException e) {
// Log the error
System.out.println("Error fetching movie details: " + e.getMessage());

// Return a default movie


return new Movie("0000", "Default movie", "Unknown", 0.0);
}

#Async call : https://medium.com/@basecs101/spring-boot-async-annotation-make-api-


calls-asynchronous-2024-latest-dcce878d0fe2#:~:text=Spring%20Boot%20%40Async
%20Annotation%20%E2%80%94%20Make%20API%20Calls%20Asynchronous,-Build%20Non
%2Dblocking&text=The%20%40Async%20annotation%20in%20Spring,for%20the%20method%20to
%20complete.

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

@Service
public class AsyncService {
@Async
public void performAsyncTask() {
// Simulate a time-consuming task
try {
Thread.sleep(5000); // Sleep for 5 seconds
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Async task completed!");
}
}

#https://www.geeksforgeeks.org/spring-postconstruct-and-predestroy-annotation-with-
example/
->Config data files are considered in the following order:

1)Application properties packaged inside your jar (application.properties and YAML


variants).

2)Profile-specific application properties packaged inside your jar (application-


{profile}.properties and YAML variants).

3)Application properties outside of your packaged jar (application.properties and


YAML variants).

4)Profile-specific application properties outside of your packaged jar


(application-{profile}.properties and YAML variants).

->If you have configuration files with both .properties and YAML format in the same
location, .properties takes precedence.

->Spring Boot provides integration with three JSON mapping libraries:

Gson

Jackson

JSON-B

-> Configuring SSL With Java KeyStore Files


https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.ssl

->If Spring Security is on the classpath, then web applications are secured by
default. Spring Boot relies on Spring Security’s content-negotiation strategy to
determine whether to use httpBasic or formLogin.The default UserDetailsService has
a single user. The user name is user, and the password is random and is printed at
WARN level when the application starts, as shown in the following example:
You can change the username and password by providing a spring.security.user.name
and spring.security.user.password.
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#web.security

->https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#web
If you do not want to use the auto-configuration and want to take complete control
of Spring MVC, add your own @Configuration annotated with @EnableWebMvc.
Alternatively, add your own @Configuration-annotated DelegatingWebMvcConfiguration
as described in the Javadoc of @EnableWebMvc.

->https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/
#features.spring-application.lazy-initialization
SpringApplication allows an application to be initialized lazily. When lazy
initialization is enabled, beans are created as they are needed rather than during
application startup. As a result, enabling lazy initialization can reduce the time
that it takes your application to start. In a web application, enabling lazy
initialization will result in many web-related beans not being initialized until an
HTTP request is received.
A downside of lazy initialization is that it can delay the discovery of a problem
with the application. If a misconfigured bean is initialized lazily, a failure will
no longer occur during startup and the problem will only become apparent when the
bean is initialized. Care must also be taken to ensure that the JVM has sufficient
memory to accommodate all of the application’s beans and not just those that are
initialized during startup. For these reasons, lazy initialization is not enabled
by default and it is recommended that fine-tuning of the JVM’s heap size is done
before enabling lazy initialization.

Lazy initialization can be enabled programmatically using the lazyInitialization


method on SpringApplicationBuilder or the setLazyInitialization method on
SpringApplication. Alternatively, it can be enabled using the spring.main.lazy-
initialization property as shown in the following example:

#Filters
->Filters can be used for different well-known use cases like Logging,
Authentication and Security, Transaction and request manipulation.
->In order to implement your custom filter in your application, you need to
implement the Filter interface. This interface has 3 methods that needed to be
implemented and they will be called in different stages of the filter’s lifecycle.
->init
This method will be run when the filter is created and it provides an instance of
FilterConfig
->doFilter
This is the main method that helps to intercept the Servlet request process. using
FilterChain you can control the next step of the incoming request by calling the
next filter in the chain or breaking it.
->destroy
As the name of the method speaks for itself this one will be called when the filter
is destroyed for any reason.

->In order for Spring to recognize a filter, we need to define it as a bean with
the @Component annotation.
->If we have more than one filters than we have to use one more annotation @Order
->https://www.youtube.com/watch?v=_Tby7sRA4hs

You might also like