方法1 用org.springframework.context.ApplicationContext 的getBean方法
调用类
@RestController
@RequestMapping("/hello")
public class HelloController {
@Resource
private ApplicationContext applicationContext;
@RequestMapping("/{animal}")
public String say(@PathVariable String animal){
Hello bean = applicationContext.getBean(animal, Hello.class);
return bean.call();
}
}
接口及实现类
// 接口
public interface Hello {
String call();
}
//实现类1
@Service
public class Cat implements Hello {
@Override
public String call() {
return "喵";
}
}
//实现类2
@Service
public class Dog implements Hello {
@Override
public String call() {
return "汪";
}
}
方法2 用@Autowired注入方法参数中, 并生成Map对象
添加注解, 可以加到实现类, 避免直接使用字符串
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnimalAnnotation {
AnimalType type() default AnimalType.human;
}
Map生成类
@Component
public class HelloFactory {
private Map<String, Hello> mapServiceKeyToHello = Maps.newHashMap();
/**
* - @Autowired 可作用于方法上
* - 有参时, 会将参数内容注入, 并运行
* - 无参时, 则会直接运行, 但是spring不推荐
*/
@Autowired
private void configHelloMap(List<Hello> listHello){
mapServiceKeyToHello = listHello.stream().collect(Collectors.toMap(item->
AnnotationUtils.findAnnotation(item.getClass(), AnimalAnnotation.class).name(), Function.identity(), (first, second) -> first));
}
@Autowired
private void lookMe(){
System.out.println("who care");
}
public Hello getInstance(String animal){
return mapServiceKeyToHello.get(animal);
}
}
接口及实现类
// 接口
public interface Hello {
String call();
}
//实现类1
@AnimalAnnotation(type = AnimalType.cat)
@Service
public class Cat implements Hello {
@Override
public String call() {
return "喵";
}
}
//实现类2
@AnimalAnnotation(type = AnimalType.dog)
@Service
public class Dog implements Hello {
@Override
public String call() {
return "汪";
}
}
最后是调用类
@RestController
@RequestMapping("/hello")
public class HelloController {
// @Resource
// private ApplicationContext applicationContext;
@Resource
private HelloFactory helloFactory;
@RequestMapping("/{animal}")
public String say(@PathVariable String animal){
return helloFactory.getInstance(animal).call();
// Hello bean = applicationContext.getBean(animal, Hello.class);
// return bean.call();
}
}