处理不同环境的注解驱动依赖注入 [英] Annotation-driven dependency injection which handles different environments

查看:22
本文介绍了处理不同环境的注解驱动依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为很多专业人士不转向注解驱动依赖注入的主要原因是它不支持在开发/测试/生产环境之间切换.在许多情况下,出于开发目的,您不仅要使用不同的服务(以及它们的连接),而且有时还需要模拟它们,或创建虚拟实例.

I think the main reason why many professional does not switch to annotation-driven dependency injection is that it does not support switching between development/test/production environments. For development purposes in many cases you use not only different services (and connections for them), but sometimes you need to Mock them, or create Dummy instances.

昨天我想出了一个带有 Spring 注释的解决方案:

Yesterday I figured out one solution with Spring annotation:

    @Value("#{${env} == "production" ? realService : dummyService}")
    private SomeService service;

...这应该有效,但不是很好.

...which should work, but not nice.

我对你的解决方案或论点非常感兴趣:为什么这不是一个真正的问题;-)欢迎使用 Guice、Spring 或任何其他产品.

I would be very interested for your solutions, or arguments: why is it not a real issue ;-) Guice, Spring, or any other are welcome.

原始问题是该线程的一部分:Spring @Autowired 用法,但我认为它值得创建一个新线程.

The original issue was a part of this thread: Spring @Autowired usage, but I thought it worth a new thread to be created.

推荐答案

不幸的是,我无法对 Guice 发表评论,但正如评论中提到的,您确实可以使用 Spring 配置文件 - 如果您使用的是 Spring 3.1 或更高版本.

Unfortunately I cannot comment on Guice, but as mentioned in the comments you can indeed use Spring profiles - if you're using Spring 3.1 or later that is.

使用配置文件的基于 Java 的配置可能如下所示:

A Java based configuration using profiles could look something like:

@Configuration
@Profile("production")
public class ProductionConfig {
    @Bean 
    public SomeService someService() { ... }
}

@Configuration
@Profile("dev")
public class DevelopmentConfig {
    @Bean 
    public SomeService someService() { ... }
}

然后你的消费类又变得更简单了:

Then your consuming class then becomes simpler again:

...
@Autowired
private SomeService someService;
...

所需的配置文件可以通过系统属性激活,其中包括:

The desired profile can, amongst other ways, be activated through a system property:

-Dspring.profiles.active="production"

这在不同环境中运行应用程序时非常有用.

Which can be useful when running your application in different environments.

我个人尽量不依赖 Spring 配置文件.相反,我尝试将环境差异封装在外部属性文件中,这些文件在运行时传递给应用程序.到目前为止,这种方法效果很好,但是 ymmv.

Personally I try not to rely on Spring profiles at all. Instead I try and encapsulate environmental differences in external property files, which are passed to the application at runtime. This approach has worked well so far but ymmv.

这篇关于处理不同环境的注解驱动依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆