Spring is a popular framework in Java for building web applications. It provides useful tools and templates to make development easier, so you can focus more on building the core features of your app.
You can use the @RequestMapping annotation to connect web requests to specific methods in your code. This tells Spring what to do when it receives a particular request.
@RequestMapping("/sayhello") public String sayHello() { return "Hello, world"; }
When you use @RequestMapping at the class level, it sets a base path for all methods in that class. This way, you can organize your endpoints better.
@RequestMapping("/recipes") public class RecipeController { @GetMapping() public IterablegetAllRecipes() { return this.recipeRepository.findAll(); } }
Spring allows you to handle different types of web requests (GET, POST, PUT, DELETE) using specific annotations.
@RestController public class FlowerController { @GetMapping("/flowers") public IterablegetAllFlowers() {} @PostMapping("/flowers") public Flower addFlower() {} @PutMapping("/flowers/{id}") public Flower editFlower() {} @DeleteMapping("/flowers/{id}") public Flower deleteFlower() {} }
You can use annotations like @RequestParam to access parameters sent in web requests.
@GetMapping("/fruit") public Fruit isFruitAvailable(@RequestParam String fruitType) { return fruit.find(fruitType); }
REST controllers help you build APIs that return data in response to web requests. You can use @RestController to create these controllers.
@RestController public class LocationController { @GetMapping("/{gpsCoordinates}") public City getByCoordinates(@PathVariable String gpsCoordinates) { return this.locations.findByCoordinates(gpsCoordinates); } }
You can handle errors and return appropriate HTTP status codes using ResponseStatusException.
@GetMapping("/{id}") public Book isBookAvailable(@PathVariable String id) { if (id.matches("\d+")) { int idAsInteger = Integer.parseInt(id); return book.findByID(idAsInteger); } else { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid ID."); } }
HTTP status codes indicate the result of a web request. For example, 200 means success, 404 means not found, and 500 means server error.
HttpStatus.OK // 200 HttpStatus.NOT_FOUND // 404 HttpStatus.BAD_GATEWAY // 502
You can specify the HTTP status code that should be returned by your API using annotations.
@PostMapping("/book") @ResponseStatus(HttpStatus.CREATED) public void addNewBook(@RequestParam String title) { this.library.add(title); }
You can use @RequestBody to automatically convert JSON data from a request into a Java object.
@GetMapping("/book") public Book isBookAvailable(@RequestBody Book book) { return library.find(book); }
A Spring bean is an object that is managed by the Spring framework. It is created and maintained by Spring's IoC (Inversion of Control) container.
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ExampleApplication { public static void main(String[] args) { SpringApplication.run(ExampleApplication.class, args); } }
The @SpringBootApplication annotation is used to mark the main class of a Spring Boot application. It combines several important configurations.
This annotation enables several features in Spring Boot, like auto-configuration and component scanning.
The application context is the environment where your Spring beans live. It handles their creation and configuration.
It is created automatically when you run a Spring Boot application.
Spring Boot is a project that makes it easier to set up and run a Spring application with minimal configuration.
Spring Boot simplifies the setup of Spring applications with built-in defaults and auto-configuration.
The application.properties file is used to configure various settings of your Spring Boot application.
You can set database connections, server ports, and other configurations in this file.
JPA is a Java specification for managing database operations. It allows you to work with data in a more object-oriented way.
JPA lets you work with Java objects instead of SQL queries for database operations.
H2 is a lightweight database that can run in memory or store data on disk. It’s often used for development and testing.
H2 database can be embedded in your application or used as a standalone database.
A data model represents the structure of the data in your application. It maps Java classes to database tables.
@Entity @Table(name="Library") public class Book { @Id private Integer id; @Column(name="Title") private String title; }
JPA entities are classes that map to database tables. Each instance of the class represents a row in the table.
@Entity @Table(name="TELEVISIONS") public class Television { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; @Column(name="Brand") private String brand; }
The @Id annotation marks a field in an entity class as the primary key for the database table.
The @Id annotation identifies the primary key field in your entity class.
The @GeneratedValue annotation specifies how the primary key value should be automatically generated.
@GeneratedValue(strategy=GenerationType.IDENTITY) // Auto-generates unique IDs for new records.
Repositories in Spring Data JPA provide methods for performing CRUD (Create, Read, Update, Delete) operations on entities.
@Repository public interface PersonRepository extends CrudRepository{}
You can use Spring Data JPA repositories to interact with the database from your controllers.
@GetMapping("/people") public IterablegetAllPeople() { return this.personRepository.findAll(); }
The save method of the repository is used to insert or update entities in the database.
@PostMapping("/people") public Person createPerson(@RequestBody Person person) { return this.personRepository.save(person); }
You can find entities by their ID using methods provided by the repository interface.
@GetMapping("/people/{id}") public Person getPersonById(@PathVariable Integer id) { return this.personRepository.findById(id).orElse(null); }
JPA allows you to define relationships between entities, like one-to-many or many-to-many.
You can use annotations like @OneToMany and @ManyToOne to map relationships between entities.
Spring Data JPA lets you create custom queries to retrieve data from the database.
@Query("SELECT p FROM Person p WHERE p.lastName = :lastName") ListfindByLastName(@Param("lastName") String lastName);
Transactions ensure that a series of operations either all succeed or all fail. Spring handles transactions automatically in most cases.
Spring manages transactions for you, but you can use @Transactional to specify transaction boundaries manually
Welcome to our comprehensive collection of programming language cheatsheets! Whether you're a seasoned developer or a beginner, these quick reference guides provide essential tips and key information for all major languages. They focus on core concepts, commands, and functions—designed to enhance your efficiency and productivity.
ManageEngine Site24x7, a leading IT monitoring and observability platform, is committed to equipping developers and IT professionals with the tools and insights needed to excel in their fields.
Monitor your IT infrastructure effortlessly with Site24x7 and get comprehensive insights and ensure smooth operations with 24/7 monitoring.
Sign up now!