如题,在开发过程中经常会有这个需求,例如全国各个城市的社保授权登录爬虫,每次加一个城市都手动去添加if判断也太LOW。那该如何实现呢?
首先我们需要定义一个接口GodFather
,然后增加两个接口的实现类implA,implB
,并且给实现类加上@Component
注解。当然,如果需要多实例的话可以一并加上@Scope("prototype")
,然后利用applicationContext.getBeansOfType(GodFather.class);获取所有的实现类,然后用applicationContext的<T> T getBean(Class<T> requiredType)
获取任意数量的实例使用即可,完整代码如下:
package me.kagura.samaritan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.Map;
@SpringBootApplication
public class SamaritanApplication {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger("https://kagura.me");
ConfigurableApplicationContext applicationContext = SpringApplication.run(SamaritanApplication.class, args);
Map<String, GodFather> beans = applicationContext.getBeansOfType(GodFather.class);
beans.forEach((name, son) -> {
logger.warn("");
logger.warn("当前类是 : " + name);
logger.warn("son.say() = " + son.say());
logger.warn("getBean = " + applicationContext.getBean(son.getClass()).toString());
logger.warn("getBean = " + applicationContext.getBean(son.getClass()).toString());
});
}
}
interface GodFather {
String say();
}
@Component
@Scope("prototype")//使用多例模式
class implA implements GodFather {
@Override
public String say() {
return "implA";
}
}
@Component
@Scope("prototype")//使用多例模式
class implB implements GodFather {
@Override
public String say() {
return "implB";
}
}
未经允许不得转载:鹞之神乐 » SpringBoot中获取某个接口的所有实现类