在Java中实现“按类型自动装配所有接口”可以使用Spring框架中的自动装配功能。以下是一个解决方法的示例:
public interface MyInterface {
void myMethod();
}
@Component
public class MyInterfaceImpl1 implements MyInterface {
@Override
public void myMethod() {
System.out.println("MyInterfaceImpl1");
}
}
@Component
public class MyInterfaceImpl2 implements MyInterface {
@Override
public void myMethod() {
System.out.println("MyInterfaceImpl2");
}
}
标签来扫描并装配所有带有@Component注解的类:
@Autowired注解进行自动装配:@Component
public class MyAutowiredClass {
@Autowired
private List myInterfaces;
public void executeMethods() {
for (MyInterface myInterface : myInterfaces) {
myInterface.myMethod();
}
}
}
这样,Spring框架会自动扫描并装配所有实现了MyInterface接口的类,然后注入到List中。调用executeMethods()方法时,会执行所有实现类的myMethod()方法。
注意:在上述示例中,使用了@Component注解来标记类,表示它们是Spring管理的组件。如果你使用的是其他注解如@Service、@Repository等,只需将示例中的@Component替换为相应的注解即可。
上一篇:按类型重新分组的行的条件求和
下一篇:按类型自动装配在接口实现中失败