spring 根据不同参数值,获取不同的接口实现类

方法1 用org.springframework.context.ApplicationContextgetBean方法

调用类

@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();
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容