1.
Spring Framework Basics
What is Spring Framework?
Answer: Spring is a comprehensive framework for enterprise Java development. It provides
infrastructure support for developing Java applications. Spring is modular, meaning you can use just the
parts you need. Its core features include dependency injection and aspect-oriented programming.
What are the key features of the Spring Framework?
Answer:
Dependency Injection
Aspect-Oriented Programming (AOP)
Transaction Management
MVC Framework
Spring JDBC
Spring ORM
Spring Test
2. Dependency Injection
What is Dependency Injection?
Answer: Dependency Injection (DI) is a design pattern used to implement IoC (Inversion of Control). It
allows the creation of dependent objects outside of a class and provides those objects to a class. This
promotes loose coupling and enhances testability and maintainability.
What are the different types of Dependency Injection?
Answer:
Constructor Injection
Setter Injection
Field Injection
How do you perform Dependency Injection in Spring?
Answer: In Spring, DI can be performed using:
XML Configuration
Annotation-Based Configuration (@Autowired, @Inject, @Resource)
Java-Based Configuration (@Configuration, @Bean)
What are the benefits of Dependency Injection?
Answer:
Decouples the construction of dependencies from the class itself.
Enhances testability by allowing mock implementations to be injected.
Promotes cleaner and more maintainable code.
3. Spring Beans
What is a Spring Bean?
Answer: A Spring Bean is an object that is instantiated, assembled, and managed by the Spring IoC
container. Beans are defined in Spring configuration files (XML or Java annotations).
How do you define a Bean in Spring?
Answer:
XML Configuration:
xml
Copy code
<bean id="beanName" class="com.example.MyClass"/>
Annotation-Based Configuration:
java
Copy code
@Component
public class MyClass { }
Java-Based Configuration:
java
Copy code
@Configuration
public class AppConfig {
@Bean
public MyClass myClass() {
return new MyClass();
}
What are the different Bean Scopes in Spring?
Answer:
Singleton: (Default) A single instance per Spring IoC container.
Prototype: A new instance each time it is requested.
Request: A single instance per HTTP request (only for web applications).
Session: A single instance per HTTP session (only for web applications).
Global Session: A single instance per global HTTP session (only for web applications).
Explain the lifecycle of a Spring Bean.
Answer:
1. Instantiation: The container instantiates the bean.
2. Populate Properties: Dependency injection occurs.
3. BeanNameAware: If the bean implements BeanNameAware, the container passes the bean’s ID.
4. BeanFactoryAware: If the bean implements BeanFactoryAware, the container passes an
instance of BeanFactory.
5. Pre-Initialization: The BeanPostProcessor interface allows for custom modification before
initialization.
6. InitializingBean: If the bean implements InitializingBean, its afterPropertiesSet method is called.
7. Custom init-method: Any custom init-method specified in the configuration.
8. Post-Initialization: The BeanPostProcessor interface allows for custom modification after
initialization.
9. Ready to use: The bean is ready to be used by the application.
10. DisposableBean: If the bean implements DisposableBean, the container calls its destroy method.
11. Custom destroy-method: Any custom destroy-method specified in the configuration.
4. Spring AOP (Aspect-Oriented Programming)
What is Aspect-Oriented Programming (AOP)?
Answer: AOP is a programming paradigm that aims to increase modularity by allowing the separation of
cross-cutting concerns (e.g., logging, transaction management). It does this by adding additional
behavior to existing code without modifying the code itself.
What are the key concepts in AOP?
Answer:
Aspect: A modularization of a concern that cuts across multiple classes.
Join Point: A point during the execution of a program, such as the execution of a method or the
handling of an exception.
Advice: Action taken by an aspect at a particular join point.
Pointcut: A predicate that matches join points.
Introduction: Adding methods or fields to an existing class.
Weaving: Linking aspects with other application types or objects to create an advised object.
Explain the types of advice in Spring AOP.
Answer:
Before Advice: Runs before the method execution.
java
Copy code
@Before("execution(* com.example.service.*.*(..))")
public void beforeAdvice() {
// logic
After (finally) Advice: Runs after the method execution, regardless of its outcome.
java
Copy code
@After("execution(* com.example.service.*.*(..))")
public void afterAdvice() {
// logic
After Returning Advice: Runs after the method execution only if it completes successfully.
java
Copy code
@AfterReturning("execution(* com.example.service.*.*(..))")
public void afterReturningAdvice() {
// logic
}
After Throwing Advice: Runs if the method exits by throwing an exception.
java
Copy code
@AfterThrowing("execution(* com.example.service.*.*(..))")
public void afterThrowingAdvice() {
// logic
Around Advice: Runs before and after the method execution.
java
Copy code
@Around("execution(* com.example.service.*.*(..))")
public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
// logic before method execution
Object retVal = pjp.proceed();
// logic after method execution
return retVal;
5. Spring MVC
What is Spring MVC?
Answer: Spring MVC is a framework for building web applications using the Model-View-Controller
design pattern. It provides a clean separation between model, view, and controller, making it easier to
manage application complexity.
How does Spring MVC work?
Answer:
1. DispatcherServlet: Receives request and delegates it to the appropriate controller.
2. Controller: Processes the request and returns a ModelAndView object.
3. Model: Data returned by the controller.
4. View Resolver: Maps the ModelAndView object to an actual view.
5. View: Renders the output to the user.
How do you define a Controller in Spring MVC?
Answer:
java
Copy code
@Controller
public class MyController {
@RequestMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello, Spring MVC!");
return "hello";
What is a @RestController in Spring?
Answer: @RestController is a specialized version of the @Controller annotation that combines
@Controller and @ResponseBody. It is used to create RESTful web services and returns the response
directly to the caller without the need for a view resolver.
6. Spring Boot Basics
What is Spring Boot?
Answer: Spring Boot is an extension of the Spring framework that simplifies the setup, configuration,
and deployment of Spring applications. It provides defaults for code and annotation configuration to
quick-start new Spring projects with embedded servers like Tomcat, Jetty, etc.
What are the advantages of using Spring Boot?
Answer:
Simplifies configuration with opinionated defaults.
Reduces development time with embedded servers.
Provides production-ready features like metrics and health checks.
Easily integrates with various databases and third-party tools.
Simplifies dependency management with Spring Boot Starters.
What is a Spring Boot Starter?
Answer: Spring Boot Starters are a set of convenient dependency descriptors you can include in your
application. They provide a ready-to-use set of libraries for various functionalities like web development,
data access, security, etc. Example: spring-boot-starter-web, spring-boot-starter-data-jpa.
7. Spring Boot Annotations
What are the important Spring Boot annotations?
Answer:
@SpringBootApplication: Marks the main class of a Spring Boot application.
@EnableAutoConfiguration: Enables Spring Boot’s auto-configuration mechanism.
@ComponentScan: Automatically scans for components, configurations, and services in the
specified package.
@RestController: Combines @Controller and @ResponseBody to simplify the creation of
RESTful web services.
@RequestMapping: Maps HTTP requests to handler methods of MVC and REST controllers.
What does @SpringBootApplication do?
Answer: @SpringBootApplication is a convenience annotation that combines @Configuration,
@EnableAutoConfiguration, and @ComponentScan with their default attributes.
8. Spring Boot Configuration
How do you configure properties in Spring Boot?
Answer: Properties can be configured in application.properties or application.yml files. For example:
properties
Copy code
server.port=8081
spring.datasource.url=jdbc
4o
complete your response
ChatGPT
Certainly! Let's continue with the remaining sections for a comprehensive guide to Spring and Spring
Boot interview questions and answers.
8. Spring Boot Configuration (Continued)
How do you access properties in Spring Boot?
Answer: You can access properties using the @Value annotation or @ConfigurationProperties:
java
Copy code
@Value("${property.name}")
private String propertyName;
Or using @ConfigurationProperties:
java
Copy code
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
// getters and setters
How do you define multiple profiles in Spring Boot?
Answer: Define profiles in application-{profile}.properties or application-{profile}.yml files and activate
them using spring.profiles.active property in application.properties or using VM arguments.
How do you manage application lifecycle events in Spring Boot?
Answer: Implement ApplicationListener or use @EventListener annotation to handle application events
such as context refreshed, application started, etc.
9. Spring Boot Actuator
What is Spring Boot Actuator?
Answer: Spring Boot Actuator provides production-ready features to help you monitor and manage your
application. It includes endpoints for health checks, metrics, info, environment, and more.
How do you enable Spring Boot Actuator?
Answer: Include the dependency in your pom.xml or build.gradle file:
xml
Copy code
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Then, access the endpoints like /actuator/health, /actuator/info.
How do you customize Actuator endpoints in Spring Boot?
Answer: You can customize Actuator endpoints using properties in application.properties or
application.yml. For example:
properties
Copy code
management.endpoints.web.exposure.include=health,info,metrics
10. Spring Boot Testing
How do you test Spring Boot applications?
Answer: Spring Boot provides extensive support for testing. Key annotations include:
@SpringBootTest: Loads the complete application context.
@WebMvcTest: Focuses only on Spring MVC components.
@DataJpaTest: Configures an in-memory database for JPA testing.
@MockBean: Mocks a bean in the application context.
java
Copy code
@SpringBootTest
public class MyServiceTest {
@Autowired
private MyService myService;
@Test
public void testMyService() {
assertEquals("expected", myService.method());
How do you mock dependencies in Spring Boot tests?
Answer: Use @MockBean to mock dependencies in integration tests:
java
Copy code
@SpringBootTest
public class MyServiceTest {
@Autowired
private MyService myService;
@MockBean
private DependencyService dependencyService;
@Test
public void testMyServiceWithMock() {
when(dependencyService.getData()).thenReturn("mocked data");
assertEquals("expected", myService.method());
11. Spring Boot Security
How do you implement security in Spring Boot?
Answer: Include the Spring Security dependency and configure security settings. For example:
xml
Copy code
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Configure security:
java
Copy code
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().permitAll()
.and()
.logout().permitAll();
What is CSRF protection in Spring Security?
Answer: CSRF (Cross-Site Request Forgery) protection is a security feature that prevents unauthorized
commands from being transmitted from a user that the website trusts. Spring Security includes CSRF
protection by default.
12. Spring Boot DevTools
What is Spring Boot DevTools?
Answer: Spring Boot DevTools is a set of tools that can make the development process more efficient. It
includes features like automatic restart, live reload, and configurations for development vs. production
environments.
How do you enable DevTools in a Spring Boot application?
Answer: Include the DevTools dependency in your pom.xml or build.gradle file:
xml
Copy code
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
What are the benefits of using Spring Boot DevTools?
Answer:
Automatic restart of the application on code changes.
Live reload of templates and static content.
Configuration properties for different environments (development, production).