Intro to Spring framework (concept)
Computer Science · Java
Question 1 of 10
0Which annotation on a service method wraps its database work in a transaction?
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Intro to Spring framework (concept) explained
Spring is a Java framework that creates and connects the objects of an application for you. Its central idea is dependency injection: instead of a class creating the objects it needs, Spring creates them and supplies them, which keeps classes loosely coupled and easier to test.
Spring keeps the objects it manages, called beans, in a container called the application context. An annotation such as @Component or @Service marks a class for Spring to manage, and Spring creates one instance of it by default. A class that needs another bean declares it as a constructor parameter, and Spring passes in the matching bean. This is inversion of control: the framework controls how objects are created and connected. Spring Boot adds sensible defaults and an embedded web server, so a project can start with little configuration. The annotations shown here are only the starting point of a large framework.
@Service
class GreetingService {
String greet(String name) {
return "Hello, " + name;
}
}
@Component
class Welcome {
private final GreetingService service;
Welcome(GreetingService service) {
this.service = service;
}
}
Worked example
Trace how Spring handles the two classes above.
- Spring finds @Service on GreetingService and creates one instance of it.
- Spring finds @Component on Welcome and sees that its constructor needs a GreetingService.
- It passes the existing GreetingService bean into that constructor, so Welcome never calls new itself.
- In a test, you can pass a fake GreetingService to Welcome directly, without changing Welcome.
What you will practise
105 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.
Example questions
- Spring is:
- Dependency injection:
- A bean is:
- Spring Boot:
- @RestController:
- Which annotation is placed on the main class of a Spring Boot application?
- Which annotation marks a class as a service-layer component?
- Which annotation maps an HTTP GET request to a method in a Spring controller?
…and 97 more.