我是Spring的新手,刚刚被分配到Spring / Java项目上工作。
SftpAccessPoint将接口作为字段(mCertificateRepository)。此字段连接到静态内部类(DependencyProvider)内的方法,如下所示。
public class SftpAccessPoint {
private static CertificateRepository mCertificateRepository;
public static class DependencyProvider {
@Autowired
public void setCertificateRepository(final CertificateRepository pCertificateRepository) {
SftpAccessPoint.mCertificateRepository = pCertificateRepository;
}
}
}
relavant bean的配置如下:
<bean id="certificateRepositoryImpl" class="com.full.appservices.impl.CertificateRepositoryImpl" />
<bean class="com.connector.sftp.accesspoint.SftpAccessPoint$DependencyProvider" />
当app在app服务器上部署时,一切正常,但是在运行集成测试时,CertificateRepositoryImpl中的一些方法不起作用,因为在该上下文中没有运行app server。
所以我编写了另一个CertificateReposity实现,它以不同的方式实现了这几个方法,并将其余的方法委托给其他实现,如下所示:
public class MockCertificateRepository implements CertificateRepository {
protected CertificateRepository mCertificateRepo = null;
public MockCertificateRepository(CertificateRepository certificateRepo) {
mCertificateRepo = certificateRepo;
}
public boolean canDeactivateCertificate() {
return mCertificateRepo.canDeactivateCertificate();
}
public void downloadDefaultSSHKey(OutputStream arg0, boolean arg1) {
// a new implementation
}
}
我假设我需要在代码中添加一些注释,并为我的测试上下文创建一个带有Bean配置的xml。我怎样才能实现以下目标? :
*我已从上面的代码清单中删除了所有不相关的行。
*我非常不愿意改变SftpAccessPoint,除非没有其他好的选择
答案 0 :(得分:0)
Spring有配置文件的概念。这意味着您可以根据应用程序设置指定将不同的bean集加载到应用程序上下文中。完整的文档在这里:http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html。但实质上,您可以为每个环境设置一组单独的定义。在你的情况下像这样:
<beans profile="test">
<bean id="certificateRepositoryImpl" class="...MockCertificateRepository" />
</beans>
<beans profile="production">
<bean id="certificateRepositoryImpl" class="...CertificateRepositoryImpl" />
</beans>
<beans profile="common"/>
然后在你的application.properties中启用了这些:
spring.profiles.active=dev,common
或
spring.profiles.active=production,common
答案 1 :(得分:0)
在测试应用程序上下文配置中尝试这样的事情。
<bean class="com.connector.sftp.accesspoint.SftpAccessPoint$DependencyProvider" />
<bean id="mockCertificateRepository" class="com.full.appservices.impl.MockCertificateRepository">
<constructor-arg>
<bean id="certificateRepositoryImpl" class="com.full.appservices.impl.CertificateRepositoryImpl" />
</constructor-arg>
</bean>