Junior — Middle
How is the architecture of a Spring application structured and what are its main layers?
sobes.tech AI
Answer from AI
The architecture of a Spring application is usually built on a multi-layered principle, which facilitates maintenance and development of the code. The main layers:
- Controllers — handle HTTP requests, accept data from the client, and return responses.
- Service layer — contains the business logic of the application, implements core operations.
- Data access layer (Repository/DAO) — responsible for interaction with the database, usually implemented using Spring Data.
- Model (Entity) — classes that describe the data structure.
Example structure:
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
return userService.getUserById(id);
}
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {}
@Entity
public class User {
@Id
private Long id;
private String name;
// getters and setters
}
Such separation increases modularity and makes testing easier.