2
2
.
.
8
8
.
.
6
6
I
I
n
n
s
s
t
t
a
a
n
n
t
t
i
i
a
a
t
t
e
e
S
S
e
e
r
r
v
v
i
i
c
c
e
e
-
-
U
U
s
s
i
i
n
n
g
g
I
I
n
n
t
t
e
e
r
r
f
f
a
a
c
c
e
e
-
-
@
@
A
A
u
u
t
t
o
o
w
w
i
i
r
r
e
e
d
d
I
I
n
n
f
f
o
o
[
[
G
G
]
]
In this step we will introduce Service Interface to decouple Controller from specific Service implementation.
Inside Controller we will just reference this interface and not any specific implementation of it.
In other words Spring will create and Object from a Service Class that implements this Service Interface.
Since we will have only one Service Class that implements this Service Interface Spring will know which one to use.
If there are multiple Classes that Implements the same Interface then you can use @Primary, @Qualifier or @Profile to
tell Spring from which Implementation to create instance.
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: @Controller, @RequestMapping, Tomcat Server
MyController
http://localhost:8080/Hello
hello()
MyServiceImpl...
Browser
Tomcat
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_service_interface_autowired (add Spring Boot Starters from the table)
Create Package: controllers (inside main package)
– Create Class: MyController.java (inside package controllers)
Create Package: services (inside main package)
– Create Class: MyServiceInterface.java (inside package controllers)
– Create Class: MyServiceImplementation.java (inside package controllers)
MyServiceInterface.java
package com.ivoronline.springboot_service_interface_autowired.services;
public interface MyServiceInterface {
public String hello();
}
MyServiceImplementation.java
package com.ivoronline.springboot_service_interface_autowired.services;
import org.springframework.stereotype.Service;
@Service
public class MyServiceImplementation implements MyServiceInterface {
public String hello() {
return "Hello from Service";
}
}
MyController.java
package com.ivoronline.springboot_service_interface_autowired.controllers;
import com.ivoronline.springboot_service_interface_autowired.services.MyServiceInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@Autowired MyServiceInterface myService;
@ResponseBody
@RequestMapping("/Hello")
public String hello() {
//CALL SERVICE
String result = myService.hello();
//RETURN RESULT
return result;
}
}
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>