Annotation-driven dependency injection which handles different environments

前端 未结 2 1045
粉色の甜心
粉色の甜心 2020-12-28 21:56

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/produc

2条回答
  •  灰色年华
    2020-12-28 22:40

    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.

    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.

提交回复
热议问题