Annotation-driven dependency injection which handles different environments

前端 未结 2 1026
粉色の甜心
粉色の甜心 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:21

    @Value annotation doesn't work the way you have tried. It can only give you values in form of String. For what you want to achieve you can try Spring Profiles as suggested by @ShyJ.

    Hope this helps you. Cheers.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题