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

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

问题描述

我觉得为什么许多专业不切换到注解驱动的依赖注入的主要的原因是,它不支持开发/测试/生产环境之间的切换。在许多情况下,开发目的使用,不仅不同的服务(和连接他们的),但有时你需要嘲笑他们,或者创建虚拟实例。

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.

我将是您的解决方案,或参数很感兴趣:为什么它不是一个真正的问题;-)
吉斯,春天,或任何其他的欢迎。

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

最初的问题是该线程的一部分:春@Autowired使用,但我认为它值得要创建一个新的线程。

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

推荐答案

不幸的是我不能评论吉斯,但在评论中提到的,你的确可以使用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.

我个人尽量不依靠弹簧的配置文件在所有。相反,我尝试和封装外部属性文件,这是传递给应用程序在运行时环境的差异。这种做法一直运作良好,到目前为止,但情况因人而异。

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天全站免登陆