2
2
.
.
9
9
.
.
5
5
I
I
n
n
t
t
e
e
r
r
f
f
a
a
c
c
e
e
-
-
@
@
P
P
r
r
i
i
m
m
a
a
r
r
y
y
I
I
n
n
f
f
o
o
[
[
G
G
]
]
In previous step we had a single Service Class that implements Service Interface.
This way Spring knew which Service Class to auto wire.
But if you have multiple Service Classes that implement the same Service Interface then you have to specify which to use.
There are two ways to instruct Spring which Implementation to inject inside the Controller
@Primary Annotation is attached to the Class that implements Interface
@Qualifier Annotation is used in combination with @Autowired
In this step we will create two Service Classes and use @Primary Annotation to tell Spring which one to inject
MyServiceImplementation1 that returns "Hello"
MyServiceImplementation2 that returns "Hello World"
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: @Controller, @RequestMapping, Tomcat Server
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_autowired_primary (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 Interface: MyServiceInterface.java (inside package controllers)
Create Class: MyServiceImplementation1.java (inside package controllers)
Create Class: MyServiceImplementation2.java (inside package controllers)
MyController
http://localhost:8080/Hello
Tomcat
Browser
MyServiceInterface
@Primary
MyServiceImpl1
MyServiceImpl2
MyServiceInterface.java
package com.ivoronline.springboot_autowired_primary.services;
public interface MyServiceInterface {
public String sayHello();
}
MyServiceImplementation1.java
package com.ivoronline.springboot_autowired_primary.services;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
@Service
@Primary
public class MyServiceImplementation1 implements MyServiceInterface {
public String sayHello() {
return "Hello";
}
}
MyServiceImplementation2.java
package com.ivoronline.springboot_autowired_primary.services;
import org.springframework.stereotype.Service;
@Service
public class MyServiceImplementation2 implements MyServiceInterface {
public String sayHello() {
return "Hello World";
}
}
MyController.java
package com.ivoronline.springboot_autowired_primary.controllers;
import com.ivoronline.springboot_autowired_primary.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() {
String Results = myService.sayHello();
return Results;
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s