This tutorial demonstrates @Qualifier injection in OfficeFloor REST service methods. When the Spring application context contains multiple beans of the same type, annotating a service method parameter with @Qualifier("name") selects the specific bean to inject.
The tutorial defines two Greeter implementations — one formal, one casual — and exposes each at its own endpoint.
<dependency> <groupId>net.officefloor.springboot</groupId> <artifactId>officefloor-rest-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
@SpringBootApplication
public class SpringRestQualifierApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRestQualifierApplication.class, args);
}
}
Greeter interfacepublic interface Greeter {
String greet(String name);
}
Each implementation is annotated with both @Component and @Qualifier, giving it a distinct qualifier name that OfficeFloor can match against service method parameters:
@Component
@Qualifier("formal")
public class FormalGreeter implements Greeter {
@Override
public String greet(String name) {
return "Good day, " + name + ".";
}
}
@Component
@Qualifier("casual")
public class CasualGreeter implements Greeter {
@Override
public String greet(String name) {
return "Hey " + name + "!";
}
}
@Qualifier("formal") on the parameter tells OfficeFloor to inject the formal bean. @Qualifier("casual") selects the casual bean. The name query parameter defaults to World when not supplied:
public class FormalGreetingService {
public void service(
@RequestParam(name = "name", required = false, defaultValue = "World") String name,
@Qualifier("formal") Greeter greeter,
ObjectResponse<String> response) {
response.send(greeter.greet(name));
}
}
public class CasualGreetingService {
public void service(
@RequestParam(name = "name", required = false, defaultValue = "World") String name,
@Qualifier("casual") Greeter greeter,
ObjectResponse<String> response) {
response.send(greeter.greet(name));
}
}
service: class: net.officefloor.tutorial.springrestqualifier.FormalGreetingService
service: class: net.officefloor.tutorial.springrestqualifier.CasualGreetingService
@SpringBootTest
@AutoConfigureMockMvc
public class SpringRestQualifierTest {
@Autowired
private MockMvc mvc;
@Test
public void formalGreeting() throws Exception {
mvc.perform(get("/greet/formal?name=Daniel").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Good day, Daniel.")));
}
@Test
public void casualGreeting() throws Exception {
mvc.perform(get("/greet/casual?name=Daniel").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hey Daniel!")));
}
}
The Spring REST Data JPA tutorial demonstrates Spring Data JPA integration with OfficeFloor transaction governance.