2015-10-06 78 views
1

Grails 2.4.5在这里。我做了一个grails create-service com.example.service.Simple它创造了一个SimpleService对我来说,我再修改,看起来像这样:配置和注入Grails服务

class SimlpeService { 
    SimpleClient simpleClient 

    Buzz doSomething(String derp) { 
     // ... 
     Fizz fizz = simpleClient.doSomething(derp) 
     // ... 
     fizz.asBuzz() 
    } 
} 

我现在可以“注入”控制器与SimpleService像这样:

class MyController { 
    SimpleService simpleService 

    def index() { 
     // etc... 
    } 
} 

但我怎么使用正确的SimpleClient实例配置/连线SimpleService。让我们假设SimpleClient通常是建立像这样:

SimpleClient simpleClient = SimpleClientBuilder 
    .withURL('http://simpleclientdev.example.com/simple') 
    .withAuth('luggageCombo', '12345') 
    .isOptimized(true) 
    .build() 

根据我在什么样的环境,我可能希望我SimpleClient实例连接simpleclientdev.example.comsimpleclientqa.example.com,甚至simpleclient.example.com。此外,我可能会使用不同的身份验证凭据,我可能不希望它被“优化”等。关键是:如何将SimpleServiceSimpleClient实例注入?

+0

为什么不创建一个服务来配置并返回一个'SimpleClient',根据你的配置为你的环境配置(例如'Config.groovy')?这就是我接近它的方式...... –

回答

1

您可以使用Java的PostConstruct注解你的方法之一,为您服务,做你想做的东西。从该文档:

PostConstruct注释用于在需要后依赖关系注入完成到执行任何 初始化要 执行的方法。

SimpleService.groovy

import javax.annotation.PostConstruct 

class SimlpeService { 

    private SimpleClient simpleClient 

    def grailsApplication 

    @PostConstruct 
    void postConstruct() { 
     def config = grailsApplication.config.client.data 

     SimpleClient simpleClient = SimpleClientBuilder 
      .withURL(config.url) 
      .withAuth('luggageCombo', config.username) 
      .isOptimized(config.optimized) 
      .build() 
    } 

    Buzz doSomething(String derp) { 
     // ... 
     Fizz fizz = simpleClient.doSomething(derp) 
     // ... 
     fizz.asBuzz() 
    } 
} 

因此,Grails的或Spring将自动调用此方法postConstruct()当所有的依赖关系(在这种情况下grailsApplication)此服务被解决,任何服务方法被调用。 这已经采取关心这个方法必须调用您访问任何字段成员或SimpleService的方法之前。

现在,一切都已经配置好喜欢你提到你可能需要调用不同的URL有不同的证书,只是你必须定义它们的Config.groovy为:

environments { 
    development { 
     client { 
      data { 
       url = "simpleclientdev.example.com" 
       username = "test" 
       optimized = false 
      } 
     } 
    } 
    production { 
     client { 
      data { 
       url = "simpleclient.example.com" 
       username = "johndoe" 
       optimized = true 
      } 
     } 
    } 
} 

现在,当你做run-app与发展模式并在您的示例控制器中调用simpleService.doSomething()将自动点击带有测试凭证的simpleclientdev.example.com URL,并且当您使用生产环境部署该方法时,相同的simpleService.doSomething()方法将打到simpleclient.example.com,并且optimized设置为true

更新 这里的关键根据你的问题点是,由于服务默认情况下单,我们不会被注入的SimpleService不同实例。相反,我们正在改变与基于环境的服务相关联的价值。

0

听起来像是你需要了解更多的关于如何可能利用Spring? Grails Spring Docs

你也可以做这样的事情所以在你的服务类

@PostConstruct 
void init() { 
    //configure variables, etc here ... 
    log.debug("Initialised some Service...") 
}