获取实现某个接口的所有实现类集合

Map result = SpringBeanUtil.getApplicationContext().getBeansOfType(Interface.class);

key位 bean name,value为实例


String[] result = SpringBeanUtil.getApplicationContext().getBeanNamesForType(IPrizeInvoke.class);

返回 bean name 的String 数组



具体代码如下:

public class InitListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {


}


@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext sc = event.getServletContext();
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
Map result = ac.getBeansOfType(IMsgHandler.class);
for(Map.Entry entry:result.entrySet()){
System.out.println(entry.getKey());//默认是类名(不带报名)
System.out.println(entry.getValue().getClass());//类的全名输出
entry.getValue().handler(new Msg());//调用对象的方法输出
}
}



输出结果:

AMsgHandler
class com.lenovo.ai.msg.handler.AMsgHandler
amesssage
BMsgHandler
class com.lenovo.ai.msg.handler.BMsgHandler
bmesssage

你可能感兴趣的:(spring)