创建接口
package com.nowcoder.community.service;
public interface DemoService {
void demo();
}
编写两个实现接口
A实现方法
package com.nowcoder.community.service.impl;
import com.nowcoder.community.service.DemoService;
import org.springframework.stereotype.Service;
@Service("A")
public class bService implements DemoService {
@Override
public void demo() {
System.out.println("I am A");
}
}
B实现方法
package com.nowcoder.community.service.impl;
import com.nowcoder.community.service.DemoService;
import org.springframework.stereotype.Service;
@Service("B")
public class aService implements DemoService {
@Override
public void demo() {
System.out.println("I am B");
}
}
调用方法
package com.nowcoder.community.controller;
import com.nowcoder.community.service.DemoService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
@Controller
@RequestMapping("/alpha")
@AllArgsConstructor
public class DemoController {
private final Map<String, DemoService> demoService;
@RequestMapping("/hello")
@ResponseBody
public String sayHello() {
demoService.get("A").demo();
System.out.println("A end");
demoService.get("B").demo();
System.out.println("B end");
}
}