Grails service using a method from another service - grails

I'm building a grails app and have come across an issue when trying to instatiate a service, in a different service. Both of the services use a method defined in the other eg.
class fooService{
def barService
barService.doIt()
def getIt(){
...
}
}
class barService{
def fooService
fooService.getIt()
def doIt(){
...
}
}
When I run the app and go to where the methods are used, it brings up this error;
Error creating bean with name 'fooService':
org.springframework.beans.factory.FactoryBeanNotInitializedException: FactoryBean is
not fully initialized yet
Is this something that cannot be done in grails? Or could anyone offer any advice?
Thanks

I've had similar issues in the past, but only when both services are transactional. If it's possible to make at least one of them non-transactional then it should work as-is. If that's not possible then the fallback is to do a kind of "late binding"
class FooService {
def grailsApplication
private getBarService() {
grailsApplication.mainContext.barService
}
public methodThatUsesBarService() {
barService.doSomething()
}
}
This will look up barService in the app context at the point where it is used, rather than at the point where the FooService is created.

Service can be called by another service but not possible at time of initialization. If you want to implement this, the way should be like.
class fooService{
def barService
def getIt(){
...
}
def anotherFooMethod(){
barService.doIt();
}
}
class barService{
def fooService
def doIt(){
...
}
def anotherBarMethod(){
fooService.getIt();
}
}

All these answers are excellent and show how to handle the problem through the framework. Although, when I had this problem I realized there must be a flaw in my plan and architecture if I absolutely must have services calling each other and causing conflicts. Instead of finding a work-around I took a slightly less complicated and strait forward approach -- I restructured. I moved the offending methods from the service class into another service class. It took some refactoring, rethinking and copy/paste skills but I think the application is better for it.
I'm not saying this is better than the other answers. I'm saying, this time, with this project refactoring was a better, faster, less complicated solution. I highly recommend it.
UPDATE
Our final strategy is to refactor all "utility" service functions into a baseService class then have all other services that need the utility services extend baseService. The new policy is to avoid injecting services into other services, unless some situation arises that doesn't allow us to follow this inheritance pattern. This will give us a cleaner code base and less of a spaghetti trail of injections to follow. Plus, it eliminates the emergence of this error.

That's not valid code, so it's hard to know what's really going on. Are the doIt() and getIt() calls in constructors? If so, change the services to implement org.springframework.beans.factory.InitializingBean and do the calls in the afterPropertiesSet method.

You can handle the circular reference using the following -
Lets call it firstSerivce and secondService.
Code changes for secondService class
protected def firstService
def grailsApplication
def initialize() {
this.firstService = grailsApplication.mainContext.firstService
}
code changes in Bootstrap.groovy
def secondService
def init = { servletContext ->
secondService.initialize()
...
..

Related

How to mock a private class method with rspec?

Hey Folks!
I'm researching a way to mock a private class method.
Before I we begin I'd like to give you some context. Firstly I am not doing this on production, initially I tried to mock it (the private class method) and decided against it, partly because I realised it was just wrong to do so and partly because I couldn't figure out how to do it 😁.
On that note some part of me felt that, somewhat ironically, the right way was a cop out 🙈. So now I am trying to satiate the need for knowledge 😋.
Here it goes.
So, I am testing a controller for success (status 200), which depends on the response of a class method in a module maintained by another party. This method in turn does some validation in a private class method contained in that same module. In an attempt to skip over this validation and get straight to the part where I return the data and in the process spare my testing server from incessant creation of Factory models...
I tried to:
allow(TheOtherModule.Class).to receive(:this_private_class_method).and_return(whatever)
To my great disappointment I found such things cannot be achieved like that, allow_any_instance_of was of no help either. This led to some desperate attempts like trying to:
allow(ThisModule.Class).to receive(:send).with('this_private_class_method').and_return(whatever)
...as well as some more elaborate ones like putting a converter of methods in before and after like so:
saved_private_methods = ThisModule.Class.private_methods
before :each do
ThisModule.Class.class_eval { public *saved_private_methods }
end
after :each do
ThisModule.Class.class_eval { private *saved_private_methods }
end
which just failed spectacularly because I copied it and class_eval, somewhat counterintuitively doesn't target class methods, the result of which is that the methods would be found by private_methods...uhm...method but once the conversion was attempted they would not be evaluated, so instead you have to use...
# Oh and dropped this it's overkill
# saved_private_methods = ThisModule.Class.private_methods
before :each do
ThisModule.Class.instance_eval { public :this_private_class_method }
end
after :each do
ThisModule.Class.instance_eval { private :this_private_class_method }
end
...which worked beautifully at what it was supposed to do except that rspec allow still wouldn't pick it up...
So now I am turning to the Bastion of knowledge that is SO in hopes of finding a way it could be done or at least a definite answer of why it cannot.

Grails : How do you make services available inside services?

I am currently running into an issue where I am attempting to use a service within a service however the service is null
class ApplicationService{
def someService
def someMethod(){
someService.method()//null on someService
}
}
Is there additional wiring that I need to perform for this to work? Thanks in advance for your help.
I was able to do this by using the grailsApplication and loading the service.
if(!someService){
someService = grailsApplication.classLoader.loadClass("org.company.SomeService").newInstance()
}
The most possible explanation i here is, the class behind SomeService is not a Grails service artefact thus you cannot just inject it like that.
Double check on the source code whether that class is really a service or just a Groovy class in src/groovy. The framework will treat these two differently.
Also do not attempt to inject service with manually creating the instance like your answer, that is not the correct way to do dependency injection in Grails (or in Spring).

Where to put object-cache in Grails?

I want to use some caching from the Guava-library in my Grails app. Is a service class with a non-static field and some getter the best place to put this cache into? Or should it be static or declared somewhere else?
Basic Example:
class TestService {
def getCachedValue(Test test) {
return testCache.get(test)
}
def testCache = new CacheBuilder()
.maximumSize(2000)
.weakKeys()
.weakValues()
.expireAfterWrite(30, TimeUnit.SECONDS)
.build(
new CacheLoader<Test, Date>() {
...
Using a service is the best idea for this. However, making it static is a bit unnecessary since by default services are singletons.
The fact a service is a singleton, and is exposed to not only your controllers but other artifacts within your Grails application make it a perfect fit for accessing an object cache. A single point of access.

ServiceManager Advice

I'm simply looking for advice on the best way I should handle this situation.
Right now I've got several files in a folder called Service. The files contact several functions which do random things of course. Each of these files needs access to the SM Adapter.
My question is, should I implement the ServiceManagerAwareInterface in each of these files OR should I just make a new class which implements the ServiceManagerAwareInterface and just extend my classes on the new class which implements this service?
Both ways work as they should, just not sure which way would be more proper.
If you think that your system will always rely on ZF2, both approaches are equivalent.
Now from an OO design perspective, personally I have a preference for the approach in which you extend your service then implement the ServiceManagerAwareInterface. I would even use an interface for the dependency over the ServiceLocator to protect even more my classes. Why?
Extending your classes does not cost you a lot, same for making your class depending on interfaces.
Let's take this example, Imagine you did not use this approach during a ZF1 project, during which you had probably resolved your dependencies with the Zend_Registry.
Now, let's assume you moved to a ZF2 implementation, how much time you think you'll spend refactoring your code from something like Zend_Registry::get($serviceX) to $this->getServiceManager()->get($serviceX) on your Service layer?
Now Assume you had made the choice of protecting your classes, first by creating your own Service locator interface, as simple as:
public interface MyOwnServiceLocatorInterface{
public function get($service);
}
Under ZF1 you had created an adapter class using the Zend_Registry:
public class MyZF1ServiceLocator implements MyOwnServiceLocatorInterface{
public function get($service){
Zend_Registry::get($service);
}
}
Your Service classes are not coupled to the Zend_Registry, which make the refactoring much more easier.
Now, You decide to move to ZF2 so you'll logically use the ServiceManger. You create then this new Adapter class:
public class MyZF2ServiceLocator implements
ServiceManagerAwareInterface,MyOwnServiceLocatorInterface
{
private $_sm;
public function get($service){
$this->_sm->get($service);
}
public function setServiceManager($serviceManager){
$this->_sm = $serviceManager;
}
}
Again, your Service classes are not coupled to the ZF2 ServiceManger.
Now, how would look like the configuration/registration of you Service layer on the ServiceManager. Well, you'll use your Module::getServiceConfig class for that:
//Module.php
public function getServiceConfig()
{
return array(
'factories'=>array(
'My\ServiceA'=>function($sm){
return new My\ServiceA($sm->get('My\Service\Name\Space\MyZF2ServiceLocator'));
}
//Some other config
)
}
As you can see, no refactoring is needed within your Service classes as we protected them by relying on interface and using adapters. As we used a closure factory, we don't even need to extend our Service classes and implement the ServiceLocatorAwareInterface.
Now, before concluding in my previous example i have to note that I did not treat the case in which my classes are constructed via factories, however, you can check one of my previous answers that address the factory topic but also the importance of loose coupling among an application layers.
you can add initializers to do that. It can reduce repetitive injection in getting the service that pass db adapter. OR, you can set abstract_factories, it will reduce repetitive SM registration. I just posted SM Cheatsheet here, Hope helpful :)
https://samsonasik.wordpress.com/2013/01/02/zend-framework-2-cheat-sheet-service-manager/

Spring Philosophy

Everytime I ask anyone what the Spring Framework is or what it does, they simply say to me, you remember that Hollywood principle right "Don't call me, I will call you", that's exactly what Spring Framework does.
What should I make out of this?
It means that a class doesn't manually instantiate the components that it depends on -- something (such as Spring's IoC context) gives the class an instance of each component that it needs. This is usually done either via setters for each component, or a constructor that takes all those components.
Basically instead of a class doing manual instantiation by itself:
public class Foo {
private Bar bar;
public void doStuff() {
bar = new BarImplementation();
bar.doMoreStuff();
}
}
IoC injects the dependency Bar into Foo, so that when you get a Foo object from the context, you know it's ready to use.
public class Foo {
private Bar bar;
public void setBar(Bar bar) { this.bar = bar; }
public void doStuff() {
// bar's already been set by the time this is called!
bar.doMoreStuff();
}
}
You didn't manually instantiate Bar, instead your configuration files (such as Spring XML) set it for you. Additionally, Foo is no longer tied to BarImplementation. Using interfaces allows you to insert different implementations, including mocks used for testing.
Sometimes callback models are more efficient, especially with anything to do with parsing
if you imagine the hollywood situation, its way more efficient for the "casting agent" to call everyone once they know who they are going to cast (or even not call) rather than having to keep taking calls from every applicant wanting an update.
Callbacks. :P That's what that means for me. Callbacks are functions that wait to be called.
See http://en.wikipedia.org/wiki/Inversion_of_Control
Spring does other things too but IoC/Dependency injection seems to be the most noted feature. It can help to make a system less coupled and more flexible.

Resources