Spring Interview Questions - Codespaghetti

Transcription

Spring Interview ons/SPRINGJava Spring Interview Questions, Programs and Examples to help you ace your nextTechnical interview.Table of Contents:CHAPTER 1: How To Describe Spring In InterviewsCHAPTER 2: Advantages Of Spring FrameworkCHAPTER 3: Core Spring Interview QuestionsCHAPTER 4: Spring AOP Interview QuestionsCHAPTER 5: Spring MVC Interview Questions1/35

CHAPTER 6: Spring REST Interview QuestionsCHAPTER 7: Spring Boot Interview QuestionsCHAPTER 8: Spring Batch Interview QuestionsCHAPTER 9: Spring JDBC Interview QuestionsCHAPTER 10: Spring Security Interview QuestionsCHAPTER 11: Spring Interview ResourcesCHAPTER 12: SummaryCHAPTER 13: Spring Interview Questions PDFWhat Is Spring FrameworkSpring is one of the most popular Java EE framework. Core concepts of Spring frameworkare “Dependency Injection” and “Aspect Oriented Programming”.Spring framework can be used in plain java applications to achieve loose coupling amongdifferent application components. This loose coupling is achieved by implementingdependency injection.Spring framework provides a lot of features and modules for specific tasks such as SpringMVC and Spring JDBC.Since it’s an open source framework with a lot of online resources and active communitymembers, working with Spring framework is easy and fun at same time. Some of thefeatures of spring framework are:Spring is Lightweight framework and easier to use in development.Spring provides dependency injection or Inversion of Control to write componentsthat are independent.Spring IoC container manages Spring Bean life cycle and project specificconfigurations such as JNDI lookup.Spring MVC framework can be used to create web applications as well as restful webservices capable of returning XML as well as JSON response.What Are Advantages Of Using Spring Framework?2/35

Some advantages of using Spring Framework are:Reducing direct dependencies between different components of the application,usually Spring IoC container is responsible for initializing resources or beans andinject them as dependencies.Spring framework is divided into several modules, it helps us in keeping ourapplication lightweight.Reduces the amount of boiler-plate code, such as initializing objects, open/closeresources.Spring framework support most of the Java EE features and even much more.Writing unit test cases are easy in Spring framework because our business logicdoesn’t have direct dependencies with actual resource implementation classes.Core Spring Interview QuestionsQuestion: What Are Important Spring Modules?Some of the Spring Framework modules areSpring Context: This is for dependency injection.Spring JDBC: This is for JDBC and DataSource support.Spring ORM – for ORMtools support such as Hibernate3/35

Spring AOP: This is for aspect oriented programming.Spring DAO: This is for database operations using DAO patternSpring Web: This is for creating web applications.Spring MVC: This is for Model View Controller implementation for creating webapplications, web services etc.Question: What Is Spring Bean?Spring bean is a normal java class that is initialized by Spring IoC container.Spring ApplicationContext is used to get the Spring Bean instance. And spring IoCcontainer manages the life cycle of Spring Bean.Question: What Is Spring Bean Configuration File?Spring Bean configuration file is used to define all the beans that will be initialized by Springcontext.When an instance of Spring ApplicationContext is created. It reads the spring bean xml file.Once the context is initialized, it is used to get different bean instances.Apart from Spring Bean configuration, this file also contains-Spring MVC interceptors-View resolvers-And other elements to support annotations based configurationsQuestion: How To Configure A Class As Spring Bean?There are three different ways to configure Spring Bean. And here they are1- XML Based ConfigurationIn this configuration we can use bean elements in a context file to configure a Spring Bean.For example: bean name "testBean" class "com.Codespaghetti.spring.beans.testBean" /bean 2- Java Based ConfigurationA Spring bean can also be configured by using @Bean annotation. This annotation is usedwith @Configuration class to configure a spring bean. for example:4/35

@Configuration@ComponentScan(value "com.Codespaghetti.spring.main")public class TestConfiguration {@Beanpublic TestService getService(){return new TestService();}}In order to get this bean from spring context, we need to use following codeAnnotationConfigApplicationContext contex new on.class);TestService testService contex.getBean(TestService.class);3- Annotation Based ConfigurationYou can also use @Component, @Service, @Repository and @Controller annotationswith classes to configure them as spring bean.Question: What Is Spring Bean LifeCycle?Spring Beans are initialized by Spring Container and all the dependencies are injected.When spring context is destroyed, it also destroys all the initialized beans.This works well in most of the cases but sometimes we want to initialize other resources ordo some validation before making our beans ready to use. Spring framework providessupport for post-initialization and pre-destroy methods in spring beans.We can do this by two ways1- By implementing InitializingBean and DisposableBean interfaces or2- By using init-method and destroy-method attribute in spring bean configurations.Question: What Is Bean Wiring?The process of injection spring bean dependencies while initializing it, is called spring beanwiring.Spring framework also supports the possibility of doing autowiring. We can use@Autowired annotation with fields.For auto wiring annotation to work, we need to enable annotation based configuration inspring bean. This can be done by context:annotation-config element.5/35

Question: What are different types of Spring Bean autowiring?There are four types of autowiring available in Spring framework.Autowire byNameAutowire byTypeAutowire by constructorAutowiring by @Autowired and @Qualifier annotationsQuestion: Are Spring Beans Thread Safe?The default scope of Spring bean is singleton, so there will be only one instance percontext. So this means that Spring beans are not thread safe by default.However we can change spring bean scope to request, prototype or session to achievethread-safety at the cost of performance.Question: What Are Some Design Patterns Used In TheSpring Framework?Some of the design patterns used in spring framework areSingleton PatternFactory PatternProxy PatternTemplate Method PatternFront ControllerPrototype PatternAdapter PatternData Access ObjectModel View ControllerQuestion: What Is Scope Prototype?Scope prototype means that every time an instance of the Bean is called. Spring will createa new instance and return it.This differs from the default singleton scope, where a single object instance is instantiatedonce per Spring IoC container.Question: How To Get ServletContext and ServletConfig Objects InSpring?6/35

In spring bean, container specific objects can be retrieved in the following two ways.FIRST: By Implementing a spring Aware interfacesSECOND: Using @Autowired annotation with bean variable of type ServletContext andServletConfig.Question: BeanFactory VSApplicationContext?Spring BeanFactory is an interface which represents a container that provides andmanages bean instances.ApplicationContext is an interface representing a container holding all information, andbeans in the application.It also extends the BeanFactory interface but the default implementation instantiates beanseagerly when the application starts. This behavior can be overridden for individual beans.Question: What Is Dependency Injection?Dependency Injection allows the developers to remove the hard coded dependenciesamong components and make the application loosely coupled, extendable andmaintainable.Some of the benefits of using Dependency Injection are:-Loose coupling-Separation of Concerns-Boilerplate Code reduction-Unit testing with easeQuestion: How To Implement Dependency Injection In Spring?In Spring framework dependency injection can be implemented by using Spring XML basedconfiguration or by using annotation based configuration.Question: How To Inject Beans In Spring?Beans in Spring framework can be injected in few different ways7/35

By using setter InjectionBy using constructor InjectionBy using field InjectionThe configuration can be done using XML files or annotations.Question: What Are Different Modes Of Autowiring Supported By Spring?Spring supports following modes to instruct Spring container to use autowiring fordependency injection.No:Default, no auto wiringbyName:Autowiring by property name. Spring container looks at the properties of the beans onwhich autowire attribute is set to byName in the XML configuration file and it tries to matchit with name of bean in xml configuration file.byType:Autowiring by property datatype. Spring container looks at the properties of the beans onwhich autowire attribute is set to byType in the XML configuration file.It then tries to match and wire a property if itstype matches with exactly one of the beansname in configuration file.contructor:byType mode in constructor argument.autodetect:Spring first tries to wire using autowire by constructor, if it does not work, Then spring triesto autowire by byType.Spring Aspect Oriented Interview Questions8/35

Question: What Is Aspect Oriented Programming?In Object Oriented Programming, modularity of application is achieved by classes, whereas in AOP application modularity is achieved by aspects and they are configured to cutacross different class methods.AOP takes out the direct dependency of cross-cutting tasks from classes that is notpossible in normal object oriented programming.AOP provides the way to dynamically add the cross-cutting concern before, after or aroundthe actual logic by using simple pluggable configurations.It makes the code easy to maintain. You can add/remove concerns without recompilingcomplete code.Spring AOP can be used by following 2 ways.1) By Aspect Annotation Style2) By XML Configuration StyleQuestion: What Is The Difference Between Concern and Cross-cuttingConcern In Spring AOP?Concern: can be defined as a functionality we want to implement to solve a specificbusiness problem. E.g. in any eCommerce application different concerns (ormodules) could be inventory management or user management etc.9/35

Cross cutting: concern is a concern which is applicable throughout the application, e.g.logging , security and data transfer are the concerns which are needed in almost everymodule of an application. Therefore they are termed as cross-cutting concerns.Question: What is Aspect, Advice, JointPoint and AdviceArguments in AOPAspect: Aspect is a class that implements cross-cutting concerns, such as transactionmanagement.Aspects can be a normal class configured in spring bean configuration file or it canbe spring aspect using @Aspect annotation.Advice: Advice is the action taken for a particular join point. In terms of programming, theyare methods that gets executed when a specific join point with matching pointcut is reachedin the application.Join Point: A join point is a specific point in the application such as method execution,exception handling. In Spring AOP a join points is always the execution of a method.Advice Arguments: We can pass arguments in the advice methods. We can use args()expression in the pointcut to be applied to any method that matches the argument pattern.If we use this, then we need to use the same name in the advice method from whereargument type is determined.Question: What Are Different Modes Of Autowiring Supported By Spring?Spring supports following modes to instruct Spring container to use autowiring fordependency injection.No:Default, no auto wiringbyName:Autowiring by property name. Spring container looks at the properties of the beans onwhich autowire attribute is set to byName in the XML configuration file and it tries to matchit with name of bean in xml configuration file.byType:Autowiring by property datatype. Spring container looks at the properties of the beans onwhich autowire attribute is set to byType in the XML configuration file. It then tries to matchand wire a property if its type matches with exactly one of the beans name in configurationfile.contructor:byType mode in constructor argument.autodetect:10/35

Spring first tries to wire using auto wire by constructor, if it does not work, Then spring triesto auto wire by byType.Question: What Are Some Available AOP implementationsMain java based AOP implementations are listed below :1. AspectJ2. Spring AOP3. JBoss AOPQuestion: How Many Advice Types In Spring?In spring an advice is implementation of cross-cutting concern. You can apply these onother modules of application.There are 5 types of Advices1. Before advice: Advice that executes before a join point, you need touse @Before annotation to enable it.2. After returning advice: Advice to be executed after a join pointcompletes normally. To use this advice, use @AfterReturningannotation.3. After throwing advice: Advice to be executed if a method exits bythrowing an exception. To use this advice, use @AfterThrowingannotation.4. After advice: Advice to be executed regardless of the means by whicha join point exits. To use this advice, use @After annotation.5. Around advice: Advice that surrounds a join point such as a methodinvocation. This is the most powerful kind of advice. To use this advice,use @Around annotation.Question: What Is Spring AOP Proxy?A a proxy is an object that looks like another object, but adds special functionality behindthe scene.11/35

AOP proxy is an object created by the AOP framework in order to implement the aspectcontracts in runtime.Spring AOP defaults to using standard JDK dynamic proxies for AOPproxies. T

codespaghetti.com/spring-interview-questions/ SPRING Java Spring Interview Questions, Programs and Examples to help you ace your next Technical interview. Table of Contents: CHAPTER 1: How To Describe Spring In Interviews CHAPTER 2: Advantages Of Spring Framework CHAPTER 3: Core Spring Interview Questions CHAPTER 4: Spring AOP Interview Questions CHAPTER 5: Spring MVC