这是下面的示例类

@Service("testService")
public class TestService {

    public String something() {
        return "abc";
    }

}


我想扩展该类,并让容器知道它需要从现在开始选择我的扩展类。

@Service("extendedTestService ")
public class ExtendedTestServiceMock extends TestService {

    @override
    public String something() {
        return "xyz";
    }

}


测试班

公共类TestClass扩展SpringTest {

@Autowired
@Qualifier(“ extendedTestService”)
私有ExtendedTestService testService;

公共无效testMethod(){
......
}

}


由以下原因引起:org.springframework.beans.factory.NoUniqueBeanDefinitionException:未定义类型为[TestService]的合格Bean:需要单个匹配的Bean,但找到了2:ExtendedTestServiceMock,testService
在org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:865)〜[spring-beans-3.2.8.RELEASE.jar:3.2.8.RELEASE]
在org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)〜[spring-beans-3.2.8.RELEASE.jar:3.2.8.RELEASE]
在org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor $ AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:489)〜[spring-beans-3.2.8.RELEASE.jar:3.2.8.RELEASE]中
...省略了91个通用框架



怎么解决呢?

最佳答案

尝试使用接口。

public interface TestService {
    String something();
}


实现方式:

@Service
@Qualifier("testService")
public class TestServiceImpl implements TestService { ... }


@Service
@Qualifier("testServiceMock")
public class TestServiceMockImpl implements TestService { ... }


和测试类:

public class TestClass extends SpringTest {

    @Autowired
    @Qualifier("extendedTestService")
    private TestService testService;

    ...

}

关于spring - 如何使用Spring扩展@Service,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29959033/

10-15 23:58