Spring Annotations are a powerful feature of the Spring Framework, enabling developers to manage configuration and behavior of their applications with minimal XML. By using annotations, developers can streamline their code, making it more readable and maintainable. This approach is particularly beneficial in large-scale applications where managing dependencies and configurations can become complex.
This article provides a curated selection of interview questions focused on Spring Annotations. Reviewing these questions will help you deepen your understanding of how annotations work within the Spring ecosystem, ensuring you are well-prepared to discuss their usage and benefits in a technical interview setting.
Spring Annotations Interview Questions and Answers
1. How does the @Autowired
annotation work in Spring?
The @Autowired
annotation in Spring automatically injects dependencies into a bean, reducing the need for manual dependency injection.
Example:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class Car { private Engine engine; @Autowired public Car(Engine engine) { this.engine = engine; } } @Component public class Engine { // Engine properties and methods }
In this example, the Car
class depends on the Engine
class. The @Autowired
annotation on the constructor allows Spring to inject an Engine
instance when creating a Car
.
2. Describe a scenario where you would use the @Qualifier
annotation.
The @Qualifier
annotation resolves ambiguity when multiple beans of the same type exist. It specifies which bean to inject.
Example:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @Component public class ServiceConsumer { private final Service service; @Autowired public ServiceConsumer(@Qualifier("specificService") Service service) { this.service = service; } public void executeService() { service.perform(); } } @Component @Qualifier("specificService") public class SpecificService implements Service { @Override public void perform() { System.out.println("Specific Service is performing."); } } @Component @Qualifier("anotherService") public class AnotherService implements Service { @Override public void perform() { System.out.println("Another Service is performing."); } }
Here, ServiceConsumer
depends on the Service
interface. The @Qualifier
annotation specifies that SpecificService
should be injected.
3. Write a simple example to demonstrate the use of @Value
for injecting property values.
The @Value
annotation injects property values into Spring-managed beans.
Example:
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class MyBean { @Value("${my.property}") private String myProperty; public void printProperty() { System.out.println("Property Value: " + myProperty); } }
In this example, @Value
injects the value of my.property
into myProperty
. The property can be defined in a file like application.properties
:
my.property=Hello, Spring!
4. What is the purpose of the @Primary
annotation and when would you use it?
The @Primary
annotation designates a preferred bean when multiple beans of the same type are available.
Example:
@Configuration public class AppConfig { @Bean @Primary public MyService primaryService() { return new PrimaryServiceImpl(); } @Bean public MyService secondaryService() { return new SecondaryServiceImpl(); } }
Here, PrimaryServiceImpl
is the default bean injected for MyService
.
5. What is the role of the @Transactional
annotation in method execution?
The @Transactional
annotation manages transactions declaratively, ensuring that all database operations within a method are part of a single transaction.
Example:
@Service public class UserService { @Autowired private UserRepository userRepository; @Transactional public void createUser(User user) { userRepository.save(user); } }
In this example, createUser
is executed within a transactional context.
6. Explain the use of @RestController
in a Spring Boot application.
@RestController
in Spring Boot creates RESTful web services by combining @Controller
and @ResponseBody
.
Example:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class MyRestController { @GetMapping("/greeting") public String greeting() { return "Hello, World!"; } }
Here, @RestController
defines a RESTful service, with @GetMapping
mapping HTTP GET requests to the greeting
method.
7. Write a code snippet to demonstrate the use of @RequestMapping
for mapping HTTP requests.
@RequestMapping
maps HTTP requests to handler methods in controllers.
Example:
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class MyController { @RequestMapping(value = "/hello", method = RequestMethod.GET) public String sayHello() { return "Hello, World!"; } @RequestMapping(value = "/goodbye", method = RequestMethod.POST) public String sayGoodbye() { return "Goodbye, World!"; } }
In this example, @RequestMapping
maps /hello
to sayHello
for GET requests and /goodbye
to sayGoodbye
for POST requests.
8. How does the @PathVariable
annotation work in Spring MVC?
The @PathVariable
annotation binds a URI template variable to a method parameter.
Example:
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @RequestMapping("/users/{userId}") public String getUser(@PathVariable String userId) { return "User ID: " + userId; } }
Here, @PathVariable
binds the userId
variable from the URL to the method parameter.
9. Describe how @RequestParam
is used to extract query parameters in a controller method.
The @RequestParam
annotation extracts query parameters from the URL.
Example:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @GetMapping("/greet") public String greet(@RequestParam(name = "name", required = false, defaultValue = "World") String name) { return "Hello, " + name; } }
In this example, @RequestParam
extracts the name
query parameter, defaulting to “World” if not provided.
10. Write an example to show how @ExceptionHandler
can be used to handle exceptions in a Spring controller.
The @ExceptionHandler
annotation handles exceptions at the controller level.
Example:
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class MyController { @GetMapping("/example") public String exampleMethod() { if (true) { throw new RuntimeException("An error occurred"); } return "Success"; } @ExceptionHandler(RuntimeException.class) public ResponseEntityhandleRuntimeException(RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } }
Here, handleRuntimeException
handles RuntimeException
thrown by methods in the same controller.
11. How does the @Cacheable
annotation work in Spring?
The @Cacheable
annotation caches the result of a method call.
Example:
import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class ProductService { @Cacheable("products") public Product getProductById(String productId) { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } return new Product(productId, "Sample Product"); } }
In this example, getProductById
caches its result in a cache named “products”.
12. Describe the use of @Profile
for defining bean profiles in a Spring application.
The @Profile
annotation indicates that a bean is only eligible for registration when specified profiles are active.
Example:
@Configuration public class AppConfig { @Bean @Profile("development") public DataSource devDataSource() { return new DataSource("dev-url", "dev-username", "dev-password"); } @Bean @Profile("production") public DataSource prodDataSource() { return new DataSource("prod-url", "prod-username", "prod-password"); } }
Here, devDataSource
is registered when the “development” profile is active, and prodDataSource
when the “production” profile is active.
13. Write an example to demonstrate the use of @Conditional
for conditional bean registration.
The @Conditional
annotation registers beans based on certain conditions.
Example:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean @Conditional(MyCondition.class) public MyService myService() { return new MyService(); } }
In this example, MyService
is registered if the condition in MyCondition
is met.
import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; public class MyCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return true; } }
14. Explain the use of the @PropertySource
annotation in Spring.
The @PropertySource
annotation specifies the location of properties files to be loaded into the Spring Environment.
Example:
@Configuration @PropertySource("classpath:application.properties") public class AppConfig { @Value("${property.name}") private String propertyName; }
Here, @PropertySource
loads application.properties
, and @Value
injects a specific property value.
15. What is the role of the @Import
annotation in Spring?
The @Import
annotation imports configuration classes into the current application context.
Example:
@Configuration public class AppConfig { // Bean definitions } @Configuration @Import(AppConfig.class) public class MainConfig { // Additional bean definitions }
In this example, MainConfig
imports AppConfig
, making its beans available in the application context.