注释驱动的依赖注入,处理不同的环境

BTa*_*acs 9 java spring annotations dependency-injection guice

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

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

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

......哪个应该有用,但不好看.

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

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

Jon*_*han 11

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

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

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

@Configuration
@Profile("dev")
public class DevelopmentConfig {
    @Bean 
    public SomeService someService() { ... }
}
Run Code Online (Sandbox Code Playgroud)

然后你的消费类再次变得更简单:

...
@Autowired
private SomeService someService;
...
Run Code Online (Sandbox Code Playgroud)

除其他方式外,所需的配置文件可以通过系统属性激活:

-Dspring.profiles.active="production"
Run Code Online (Sandbox Code Playgroud)

在不同环境中运行应用程序时,这可能很有用.

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