Download as pdf
Download as pdf
You are on page 1of 10
sor1r2020 ‘Spring Boot basic annotation introducing basic Spring Boot annotations ZetCode All Spring Boot Python C# Java JavaScript Subscribe Spring Boot basic annotations last modified July 6, 2020 Spring Boot basic annotations tutorial shows how to use basic Spring Boot annotations including @Bean, @Service, @Configuration, @Controller, @RequestMapping, @Repository, @Autowired, and @SpringBootApplication. Spring is a popular Java application framework for creating enterprise applications. Spring Boot is the next step in evolution of Spring framework. It helps create stand-alone, production-grade Spring based applications with minimal effort. It docs not use XML configurations anymore and implements the convention over configuration principle. Annotation is a form of metadata which provides data about a program that is not part of the program itself. Annotations do not have direct effect on the operation of the code they annotate. Spring Boot basic annotations In the example application, we have these Spring Boot annotations: @Bean - indicates that a method produces a bean to be managed by Spring. @Servi @Repository - indicates that an annotated cla indicates that an annotated class is a service class. isan s a repository, whi abstraction of data access and storage. @Configuration - indicates that a class is a configuration class that may contain bean definitions. zelcode.comispringbootannattions! 10 torn2020 ‘ping Boo bese anotatons- edu base Spring Bot anntatons + @Controller - marks the class as web controller, capable of handling the requests. * @RequestMapping - maps HTTP request with a path to a controller method. + @Autowired - marks a constructor, field, or setter method to be autowired by Spring dependency injection. * @SpringBootApplication - enables Spring Boot autoconfiguration and component scanning. @Component is a generic stereotype for a Spring managed component. It turns the class into a Spring bean at the auto-scan time. Classes decorated with this annotation are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases. There are also Hibernate @Entity, @Table, @Id, and @GeneratedValue annotations in the example. Spring Boot basic annotations example The following application is a Spring Boot application which returns data from an H2 database using Spring Data JPA. The application uses FreeMarker as a template engine. | ChtyRepository. java cityservice. java ICityService. java pom. xn L-iava | Leon | (—setcode | | Application. java | {controller | | MyController. java | '—node1 | | City java | repository | | | L, application. yam) resources | | sal impor [static | ess I style.css templates. index. fth showCities.tIh zelcode.comispringbootannattions! 20 sor1r2020 ‘Spring Boot basic annotation introducing basic Spring Boot annotations ‘test java This is the project structure. pom. xml. 4..0.0 com. zetcode springbootbasicannotations 1 .@-SNAPSHOT jar UTF-8 «maven .conpiler . source>13 13 org. springframework. boot spring-boot-starter-parent 2.2.4, RELEASE org. springframework. boot spring-boot -starter-web org. springframework. boot spring-boot -starter-freemarker org. springframework. boot spring-boot-starter-data~jpac/artifactId> com.h2database runtimec/scope> zelcode.comispringbootannattions! ano sor1r2020 ‘Spring Boot basic annotation introducing basic Spring Boot annotations org. springframework. boot spring-boot-naven-plugin ‘This is the Maven build file. It contains dependencies for Freemaker, Spring Data JPA, and He database. When Spring Boot finds Freemaker and He in the pom. xml, it automatically configures them. We can use them right away. resources/application. yml servlet: context-path: /nyapp spring: ain: banner-mode: "off" datasource platform: hz org: springframework: ERROR In the application. ym1 file we write various configuration settings of a Spring Boot application. com/zetcode/model/City. java package com.zetcode.model; import java.util.objects; import javax.persistence.entity; import javax.persistence.GeneratedValue} import javax.persistence.GenerationType; zelcode.comispringbootannattions! ano sor1r2020 ‘Spring Boot basic annotation introducing basic Spring Boot annotations import javax.persistence.Id; import javax.persistence.Table; @entity @Table(nane = "cities") public class City { @ra @seneratedvalue(strategy = GenerationType. IDENTITY) private Long id; private String nane; private int population; public City() { } public City(String name, int population) { this.name = name; this.population = population; y public Long getId() { return id; } public void setId(Long id) ¢ this.id = id } public String getNane() { return name; } public void setName(string name) { this.name = name; > public int getPopulation() ¢ return population; } public void setPopulation(int population) { this.population = population; } @override public int hashCode() { int hash = 7; hash = 79 * hash + Objects.hashCode(this. id); hash = 79 * hash + Objects.hashCode(this.name) ; hash = 79 * hash + this.population; return hash; zelcode.comispringbootannattions! 510 ‘Spring Boot basic annotation introducing basic Spring Boot annotations @override public boolean equals(Object obj) { if (this == obj) ( return true; > if (obj == null) { return false; ? if (getClass() = obj.getClass()) { return false; ? final City other = (City) obj; if (this.population return false; = other.population) { y if (JObjects.equals(this.name, other.name)) { return false; , return Objects.equals(this.id, other.id); } @override public String tostring() { builder = new StringBuilder); builder. append("City{ id=") .append(id).append(", name=") -append(name).append(", population: -append(population) .append("}")3 return builder.tostring(); ) This is the City entity. Each entity must have at least two annotations defined: @Entity and @Id. The @Entity annotation specifies that the class is an entity and is mapped to a database table. The @Table annotation specifies the name of the database table to be used for mapping. The @Id annotation specifies the primary key of an entity and the @GeneratedValue provides for the specification of generation strategies for the values of primary keys. resources/import.sql INSERT INSERT INSERT INSERT INSERT INSERT INSERT INSERT INTO INTO INTO INTO INTO INTO INTO INTO cities(nane, cities(nane, cities(nane, cities(nane, cities(nane, cities(nane, cities(nane, cities(nane, zelcode.comispringbootannattions! population) population) population) population) population) population) population) population) VALUES( ‘Bratislava’, 432000); VALUES( Budapest", 1759800); VALUES( ‘Prague’, 1280000); VALUES('Warsaw', 174800); VALUES('Los Angeles", 3971000); VALUES('New York", 855800); VALUES( Edinburgh’, 464000) ; VALUES('Berlin', 3671088); en0 sor1r2020 ‘Spring Boot basic annotation introducing basic Spring Boot annotations ‘he schema is automatically created by Hibernate; later, the import.sq] file is executed to fill the table with data. com/zetcode/repository/CityRepository.java package con, zetcode.repository; import con.zetcode.model.City; import org. springfranework.data. repository .CrudRepository; import org. springfranework.stereotype.Repository; @Repository public interface CityRepository extends CrudRepository ( } ‘The @Repository annotation is used to define a repository. com/zetcode/service/ICityService. java package com.zetcode. services import con.zetcode.model.Citys import java.util.List; public interface ICityService { Listcity> findall(); ICityService provides a contract method to get alll cities. com/zetcode/service/CityService. java package com, zetcode.services import con.zetcode.model.Citys import com. zetcode. repository .cityRepository; import java.util.List; import org. springfranework.beans.factory.annotation.Autowired; import org. springframework. stereotype. Service; @service public class CityService implements ICityService { @Autowired private CityRepository cityRepository; @override public List findAll() { zelcode.comispringbootannattions! m0 sor1r2020 ‘Spring Boot basic annotation introducing basic Spring Boot annotations return (List) cityRepository.findAll(); The @Service annotation declares CityService to be a service class; a class that provides business services. The @Autowired annotation marks cityRepository field to be injected with CityRepository. com/zetcode/controller/MyController.java package con. zetcode.controlier; import con. zetcode. service. ICityServices import org. springfranework.beans.factory.annotation.Autowired; import org.springfranework.stereotype.Controller; import org.springframework.ui Model; import org. springfranework.web.bind. annotation. RequestMapping; import org. springfranework.web. servlet .ModelAndView; import java.util.HashMap; import java.util.Map; @controller public class MyController { @autowired private ICityService cityService; G@RequestMapping(" public String index(Model model) { return "index"; } G@RequestMapping("/cities") public ModelAndView showCities() ( var cities = cityService.findAll(); MapeString, Object> params = new HashMap<>(); parans.put("cities", cities); return new ModelAndView("showCities", params); The @Controller annotation marks a class as a web controller. The @RequestMapping maps HTTP request with a path to a controller method. In the second case, it maps the /cities URL to the showCities() method. zelcode.comispringbootannattions! ano sor1r2020 ‘Spring Boot basic annotation introducing basic Spring Boot annotations resources/templates/index.ft1h Hone page This is the index. ft1h template file. It contains a link to create a request to show all cities. resources/templates/showCities.ftlh cha>List of cities <#list cities as city> ${city.id}
Name Population ${city.population}
This is the showCities..#t1h template file. It uses FreeMarker #1ist macro to display all city objects. zelcode.comispringbootannattions! eno torn2020 ‘ping Boo bese anotatons- edu base Spring Bot anntatons resources/static/css/style.css h2 {color: blue} tdinth-chila(3) ¢ text-align: rights ? This is the style. css template file. com/zetcode/Application. java package com.zetcode; import org. springfranework.boot .SpringApplication; import org.springfranework. boot .autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(string[] args) { ‘SpringApplication.run(Application.class, args); } The @SpringBootApplication enables auto-configuration and component scanning. $ mvn spring-boot :run We run the application and locate to the localhost :8@80/myapp address. In this tutorial, we have covered a few basic Spring Boot annotations. List all Spring Boot tutorials, Home Eacchook Twitter Github Subscribe Privacy zetcode.comispringbootannsttions! s010

You might also like