Bet*_*eto 3 java settings service spring spring-mvc
我有一个服务界面
interface ImageSearchService {
// methods...
}
Run Code Online (Sandbox Code Playgroud)
我有2个实现:
@Service
class GoogleImageSearchImpl implements ImageSearchService {
// methods...
}
@Service
class AzureImageSearchImpl implements ImageSearchService {
// methods...
}
Run Code Online (Sandbox Code Playgroud)
我有一个控制器使用两者之一:
@Controller
ImageSearchController {
@Autowired
ImageSearchService imageSearch; // Google or Azure ?!?
}
Run Code Online (Sandbox Code Playgroud)
如何使用Environment API设置正确的实现?
如果环境属性是my.search.impl=googlespring需要使用GoogleImageSearchImpl,或者环境my.search.impl=googlespring需要使用AzureImageSearchImpl.
您可以使用Spring Profiles实现此目的.
interface ImageSearchService {}
class GoogleImageSearchImpl implements ImageSearchService {}
class AzureImageSearchImpl implements ImageSearchService {}
Run Code Online (Sandbox Code Playgroud)
请注意,@Service已从两个实现类中删除了注释,因为我们将动态实例化这些注释.
然后,在您的配置中执行以下操作:
<beans>
<beans profile="azure">
<bean class="AzureImageSearchImpl"/>
</beans>
<beans profile="google">
<bean class="GoogleImageSearchImpl"/>
</beans>
</beans>
Run Code Online (Sandbox Code Playgroud)
如果您使用Java配置:
@Configuration
@Profile("azure")
public class AzureConfiguration {
@Bean
public ImageSearchService imageSearchService() {
return new AzureImageSearchImpl();
}
}
@Configuration
@Profile("google")
public class GoogleConfiguration {
@Bean
public ImageSearchService imageSearchService() {
return new GoogleImageSearchImpl();
}
}
Run Code Online (Sandbox Code Playgroud)
运行应用程序时,通过设置变量的值来选择要运行的配置文件spring.profiles.active.您可以将其传递给JVM -Dspring.profiles.active=azure,将其配置为环境变量等.
这是一个示例应用程序,显示Spring Profiles的运行情况.