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! 10torn2020 ‘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!
20sor1r2020 ‘Spring Boot basic annotation introducing basic Spring Boot annotations
‘test
java
This is the project structure.
pom. xml.
4..0.0com. zetcode
springbootbasicannotations1 .@-SNAPSHOTjarUTF-8
«maven .conpiler . source>13
13org. springframework. bootspring-boot-starter-parent2.2.4, RELEASEorg. springframework. boot
spring-boot -starter-weborg. springframework. bootspring-boot -starter-freemarkerorg. springframework. boot
spring-boot-starter-data~jpac/artifactId>
com.h2database
runtimec/scope>
zelcode.comispringbootannattions! anosor1r2020 ‘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!
anosor1r2020 ‘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);
en0sor1r2020 ‘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! m0sor1r2020 ‘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!
anosor1r2020 ‘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