2
2
.
.
5
5
.
.
3
3
P
P
r
r
o
o
p
p
e
e
r
r
t
t
i
i
e
e
s
s
-
-
P
P
r
r
i
i
v
v
a
a
t
t
e
e
-
-
G
G
e
e
t
t
t
t
e
e
r
r
s
s
&
&
C
C
o
o
n
n
s
s
t
t
r
r
u
u
c
c
t
t
o
o
r
r
I
I
n
n
f
f
o
o
[
[
G
G
]
]
This tutorial shows how to create Entity that has private Properties but uses Constructor instead of Setters.
You can combine Constructor and Setters where
● Constructor is used to set Required or Immutable Properties
● Setters are used to set Optional or Mutable Properties
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: @RequestMapping, Tomcat Server
PersonEntity
http://localhost:8080/Hello
Tomcat
Browser
MyController
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_entity_constructor (add Spring Boot Starters from the table)
Create Package: entities (inside main package)
– Create Class: PersonEntity.java (inside package entities)
Create Package: controllers (inside main package)
– Create Class: MyController.java (inside package controllers)
PersonEntity.java
package com.ivoronline.springboot_entity_constructor.entities;
public class PersonEntity {
//PROPERTIES
private long id;
private String name;
private Integer age;
//CONSTRUCTOR
public PersonEntity(long Id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
//GETTERS
public long getId () { return id; }
public String getName() { return name; }
public Integer getAge () { return age; }
}
MyController.java
package com.ivoronline.springboot_entity_constructor.controllers;
import com.ivoronline.springboot_entity_constructor.entities.PersonEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/Hello")
public String hello() {
PersonEntity personEntity = new PersonEntity(1, "John", 20);
return "Hello " + personEntity.getName();
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
http://localhost:8080/Hello
Application Structure
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>