有什么方法可以使用@autowired标记注入一个子对象?



public class Provider {

    @Autowired
    private ParentFeedAPI feedAPI;

}


public abstract class ParentFeedAPI {

}

public class Child1FeedAPI extends ParentFeedAPI{

}

public class Child2FeedAPI extends ParentFeedAPI{

}





Class diagram

最佳答案

您应该遵守@Qualifier批注,并使用例如@Component(或更合适的spring构造型注解),类似

public class Provider {

    @Qualifier("child1")
    @Autowired
    private ParentFeedAPI feedAPI;

}

public interface ParentFeedAPI {

}

@Component("child1")
public class Child1FeedAPI implements ParentFeedAPI{

}

@Component("child2")
public class Child2FeedAPI implements ParentFeedAPI{

}


另外,尝试针对接口进行编程

07-24 21:17