SpringAndSpringBootinterviewqsns
SpringAndSpringBootinterviewqsns
->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).
->@PropertySource,@Value("${demo.item-price}"), application.properties,
application-{profile}.properties,spring.profiles.active
->https://www.baeldung.com/circular-dependencies-in-spring
@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.
@Cacheable("piDecimals")
public int computePiDecimal(int precision) {
...
}
#https://loadninja.com/articles/optimize-api-performance/
->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.
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 {
@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
#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
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
SpringApplication.run(MyApplication.class);
// other statements
}
}
#http://localhost:8080/ex/bars?id=100
here id is RequestParam
#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);
}
@EnableRetry
@SpringBootApplication
public class SpringBootRetryApplication {
@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());
@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:
->If you have configuration files with both .properties and YAML format in the same
location, .properties takes precedence.
Gson
Jackson
JSON-B
->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.
#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