How To Store Image In Mongodb Using Spring Boot
One of the way for storing image in MongoDB is by using Spring Content. And also you should have the below dependency in your pom.xml.
< dependency> < groupId> com.github.paulcwarren< /groupId> < artifactId> spring-content-mongo-boot-starter< /artifactId> < version> 0.0.10< /version> < /dependency>
You should have a GridFsTemplate bean in your applicationContext.
@Configurationpublic class Config@Beanpublic GridFsTemplate gridFsTemplate throws Exception ...
Now add attributes so that your content will be associated to your entity.
@ContentIdprivate String contentId @ContentLength private long contentLength = 0L @MimeTypeprivate String mimeType = "text/plain" And last but not the least, add a store interface.@StoreRestResourcepublic interface GreatLearningImageStore extends ContentStore< Candidate, String>
Thats all you have to do to store your images in mongoDb using Springboot.
What Is The Spring Beans Life Cycle
Spring Beans are initialized by Spring Container and all the dependencies are also injected. When the context is destroyed, it also destroys all the initialized beans. This works well in most cases but sometimes we want to initialize other resources or do some validation before making our beans ready to use. Spring framework provides support for post-initialization and pre-destroy methods in spring beans.
We can do this in two ways â by implementing InitializingBean and DisposableBean interfaces or using init-method and destroy-method attribute in spring bean configurations. For more details, please read Spring Bean Life Cycle Methods.
You May Like: An Interview With God Explained
Q42 What Is The Difference Between Mock Or Stub
- A dummy object that helps in running the test.
- Provides fixed behavior under certain conditions which can be hard-coded.
- Any other behavior of the stub is never tested.
For example, for an empty stack, you can create a stub that just returns true for empty method. So, this does not care whether there is an element in the stack or not.
- A dummy object in which certain properties are set initially.
- The behavior of this object depends on the set properties.
- The objects behavior can also be tested.
For example, for a Customer object, you can mock it by setting name and age. You can set age as 12 and then test for isAdult method that will return true for age greater than 18. So, your Mock Customer object works for the specified condition.
You May Like: Quality Assurance Questions And Answers For Interview
Microservices Interview Questions And Answers For Experienced
Q11). How can you define the Ubiquitous Language for Microservices?
This is a specific language that can be used by developers or users to define every domain in detail. This is a crystal-clear language that brings all the team members together on the same page and translated so well that a machine can understand quickly.
Q12). How will you define coupling?
The measure of the strength of dependencies among components is said to be coupling. For a good design, cohesion is high and coupling is low.
Q13). What is the meaning of Cohesion in Microservices?
The degree to which how components bind together within a module is called the Cohesion.
Q14). What is the meaning of Spring Boot?
Spring becomes more and more complex when new features are added to an application. When you have to start a new Spring project, you should add paths and dependencies. Also, you have to define the configuration for servers, and define everything from scratch.
Spring Boot is the solution to this problem. With this feature, you can always avoid the boilerplate code and tough configurations. Basically, Spring is like an ingredient here that is needed to make a cake and Spring Boot is the complete cake in your hand.
Q15). What are RESTful web services and explain their benefits too?
Microservices can always be implemented with or without REST APIs. For easy implementation, this is always recommended using REST APIs.
Q16). What is Spring Cloud?
What Is Jpa In Spring Boot
So, when you need to connect from your java application to relational database, you need to be able to use something like JDBC and run SQL queries and then you get the results and convert them into Object instances.
ORM lets you map your entity classes in your SQL tables so that when you connect to the database , you dont need to do query yourself, its the framework that handles it for you.
And JPA is a way to use ORM, its an API which lets you configure your entity classes and give it to a framework so that the framework does the rest.
Read Also: What Questions Can You Ask In An Interview
What Do You Understand By Spring Data Rest
Refer the below example:
@RepositoryRestResourcepublic interface GreatLearningRepo extends CustomerRepository< greatlearning, Long>
Now you can use the POST method in the below manner:
And you will get response as follow:
__________," greatlearning ": }
In the above, you can see the response of the newly created resource.
What Is An Ioc Container
IoC Container is a framework that is used for implementing automatic dependency injection. It manages object creation and its lifetime. It, it also injects dependencies into the class.
The IoC container is used to create an object of the specified class. It also injects all the dependency objects through a constructor, a property, or a method at run time and disposes it at the appropriate time. With this, one doesnt have to create and manage objects manually.
All the containers provide easy support for the Dependency Injection lifecycle as below.
Register: The container should know which dependency to instantiate when it encounters a particular type. This process is called registration.
Resolve: When using the IoC container, the objects need to be created manually. This is done by the container and is called resolution. The container should include some methods to resolve the specified type the container creates an object of the specified type. It then injects the required dependencies if any and returns the object.
Dispose: The container should manage the lifetime of the dependent objects. IoC containers include different lifetime managers to manage an objects lifecycle and dispose it.
Also Check: How To Dress For An Interview Women
When Should One Consider Microservice Kind Of Architecture
There are two cases.
- If you already have a monolith application and it grows to an extent where there are problems in scaling or we are not able to reutilize the components/modules/services across different projects/platforms and there is a need to do so. As well as at the same time implementing new features is painful and more error-prone and it is difficult to scale further.
- For new applications where implementation has not started yet started, we can think of a business case to be efficiently implemented, which can be easily maintainable, testable and scalable in the future and might be used across other projects/products/platforms at the same time.
Can We Create State Machines Out Of Microservices
Ans: As we know that each Microservice owning its own database is an independently deployable program unit, this, in turn, lets us create a State Machine out of it. So, we can specify different states and events for a particular microservice.
For Example, we can define an Order microservice. An Order can have different states. The transitions of Order states can be independent events in the Order microservice.
What Are Main Differences Between Microservices And Monolithic Architecture
|Microservices are loosely coupled architecture.||Monolithic architecture is mostly tightly coupled.|
|Changes done in a single data model does not affect other Microservices.||Any changes in the data model affect the entire database|
|Microservices focuses on products, not projects||Monolithic put emphasize over the whole project|
What Is End To End Microservices Testing
Ans: End-to-end testing validates each and every process in the workflow is functioning properly. This ensures that the system works together as a whole and satisfies all requirements.
In layman terms, you can say that end to end testing is a kind of tests where everything is tested after a particular period.
Also Check: How To Interview Front End Developer
What Is Spring Boot Dependency Management
Spring Boot manages dependencies and configuration automatically. Each release of spring boot provides a list of dependencies that it supports. The list of dependencies available as a part of Spring-boot dependencies can be used in maven, so we need to specify the version of the dependencies or add the dependencies version in our config file in our configuration.
Spring boot automatically manages and spring boot upgrades all dependencies automatically respectively or consistently at the time when we update the spring boot version.
- Advantage of Dependency Management:-
Example Of @get Endpoint
Below code structure represent the Rest Controller class developed using spring boot framework which use to act as Http Get method.
// Below series of import is important package specially org.springframework package.import java.util.HashMap import java.util.Map import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import com.practise.springboot.model.Product // Need to mention the RestController so that it will behave as rest end point.@RestControllerpublic class ProductServiceController // Below method act as a GET method, which is responsible to receive the HTTP GET call and return back the Product details as a response along with the HTTP Status OK. @RequestMapping public ResponseEntity< Object> getProduct }
Read Also: What To Wear To A Job Interview Female
What Are The Features Of Microservices Architecture
Hiring managers want to know how your expertise will directly benefit their organization. If you can, after explaining the features of microservices architecture, provide an example that relates directly to the company’s work. This shows that you not only understand the complexities of microservices, but you’re prepared to apply all the features directly to improving the company’s functionality.
Example:”There are several main features of microservices architecture, including Agile development, decoupling, decentralized governance, componentization, continuous delivery and its business capabilities.
Microservices allow for agile development to the individual components, allowing easy improvement and application of new features.The components are mostly independent within a microservices framework, so decoupling makes it easy to change certain components without disrupting the application as a whole.
Because of the decentralized governance feature in microservices, no single tool rules the application. Developers can use a variety of tools and supports to create the ideal application for their company. Through componentization, the individual components are easy to adjust, remove or add without impacting the application overall.
Q23 What Are Different Types Of Tests For Microservices
While working with microservices, testing becomes quite complex as there are multiple microservices working together. So, tests are divided into different levels.
- At the bottom level, we have technology-facing tests like- unit tests and performance tests. These are completely automated.
- At the middle level, we have tests for exploratory testing like the stress tests and usability tests.
- At the top level, we have acceptance tests that are few in number. These acceptance tests help stakeholders in understanding and verifying software features.
Recommended Reading: What Is The Best Answer For Job Interview
Explain How You Can Override The Default Properties Of Spring Boot Projects
By specifying properties in the application.properties file, it is possible to override the default properties of a spring boot project. Example: In Spring MVC applications, you need to specify a suffix and prefix. You can do this by adding the properties listed below in the application.properties file.
- For suffix spring.mvc.view.suffix: .jsp
Write Difference Between Monolithic Soa And Microservices Architecture
- Monolithic Architecture: It is “like a big container” where all the software components of an application are bundled together tightly. It is usually built as one large system and is one code-base.
- SOA : It is a group of services interacting or communicating with each other. Depending on the nature of the communication, it can be simple data exchange or it could involve several services coordinating some activity.
- Microservice Architecture: It involves structuring an application in the form of a cluster of small, autonomous services modeled around a business domain. The functional modules can be deployed independently, are scalable, are aimed at achieving specific business goals, and communicate with each other over standard protocols.
Don’t Miss: How Long To Prepare For Faang Interview
Difference Between Microservices And Soa
Microservices are a continuation to SOA.
SOA started gaining ground due to its distributed architecture approach and it emerged to combat the problems of large monolithic applications, around 2006.
Both of these architectures share one common thing that they both are distributed architecture and both allow high scalability. In both, service components are accessed remotely through remote access protocol . both are modular and loosely coupled by design and offer high scalability. Microservices started gaining buzz in late 2000 after the emergence of lightweight containers, Docker, Orchestration Frameworks . Microservices differ from SOA in a significant manner conceptually –
What Are Some Of The Disadvantages Of Using Spring Boot
Some of the common drawbacks of Spring Boot to keep in mind is its complexities. While working with Spring Boot, converting legacy to a full-fledged Spring Boot app could take up your time. Secondly, Spring Boots flexibility with large-scale projects isnt suitable in the long run. As a developer, if you wish to choose Spring Boot to create monolithic apps, you will be disappointed. Finally, Spring Boots lack of control could multiply dependencies that could result in the execution of massive deployment data.
How Does Pact Work
PACT is an open source tool. It helps in testing the interactions between consumers and service providers. However, it is not included in the contract, increasing the reliability of the application.The consumer service developer starts by writing a test which defines a mode of interaction with the service provider. The test includes the providers state, the request body and the response that is expected. Based on it, PACT creates a stub against which the test is executed. The output is stored in a JSON file.
How To Handle 404 Error In Spring Boot
Consider a scenario, where there are no stockDetails in the DB and still, whenever you hit the GET method you get 200 even though the resource is not found which is not expected. Instead of 200, you should get 404 error.So to handle this, you need to create an exception, in the above scenario StockNotFoundException.
GetMapping public Stock retriveStock
Now, create a Constructor from Superclass.
Right-click on the file -> Go to Source -> And generate constuctors from superclass-> and check the RuntimeException-> and generate.
And add an annotation called @ResponseStatus which will give you 404 error.
package com.greatlearning import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ResponseStatus @ResponseStatuspublic class StockNotFoundException extends RuntimeException }
Now, you can hit the same URL again and there you go, you get a 404 error when a resource is not found.
Recommended Reading: What To Ask When Conducting An Interview
How To Handle Exceptions In Microservices
In the case of microservices, exception handling is important. If any exception/error is not handled, it will be propagated to all the downstream services creating an impact on the user experience. To make the services more resilient, handling exceptions becomes very important.
In the case of 500 Internal Service Error, Sprint Boot will respond like below.
( "timestamp": "2020-04-02T01:31:08.501+00:00","path": "/shop/action","status": 500,"error": "Internal Server Error","message": "", "requestId": "a8c4c6d4-3"}
Spring provides ControllerAdvice for exception handling in Spring Boot Microservices. @ControllerAdivce informs Spring Boot that a class will act like an Interceptor in case of any exceptions.
We can have any number of exception handlers to handle each exception.
Eg. For handling generic Exception and RunTimeException, we can have 2 exception handlers.
Spring Boot Interview Questions Faqs
This FAQ section on Spring Boot interview questions covers some of the most commonly asked questions about Spring Boot, including questions about its features, working, etc.
1. What is a spring boot? Why should you use it?
Spring Boot provides a good platform for Java developers to reduce overall development time and increase efficiency by integrating tests. One can choose Spring Boot because it provides powerful batch processing, eases dependency management, and no manual configurations are needed.
2. What is the main class in spring boot?
The main class in spring boot is configured automatically by the public static void main method that starts up the Spring ApplicationContext.
3. What are the spring boot features?4. How does spring boot handle exc
Springboots exception handler is an annotation that is used to handle the specific exceptions with the help of @ExceptionHandler annotation.
5. How does spring boot Microservice discover dependent Microservices?
Eureka service can discover dependent microservices in spring boot to get the job done. This service will register all the client microservices through the eureka server to get the dependent microservice.
6. What is a bean in spring?
In Spring, the bean is defined as an object that is like a backbone of your application, managed by a Spring IoC container.
7. What is spring boot Microservices?8. What is the classpath in spring boot?9. How does spring boot application work?
Read Also: What To Wear For An Interview Female