I know the simple differences between them, but when it come to the scenario where I want to share an object instance in the app, I can done this by using DI or Singleton.
when this question come to my mind I became confused, since I can use both, I think that one of them must be better than the other in cases like multi-threading or memory management JVM or code maintainability ...
can someone tell me what is the advantages and disadvantages of using one of them over the other in the above scenario and what is the correct choice ?
Firstly, Both DI and Singleton are Design-patterns.
Dependency injection:
DI is a way of injecting dependent objects into your application.
Singleton pattern:
Create one and only instance of an object.
Source:Design patterns-Singleton
can someone tell me what is the advantages and disadvantages of using one of them over the other in the above scenario and what is the correct choose ??
DI takes care of object creation, configuration and injection. That means DI can create, configure and inject a Singleton object too. DI is helpful when you want to make object creation externalised, loosely coupled and easily maintainable.
Singleton provides only one instance of the object and where you can access the object globally. This object can be injected into the application by DI also. This is helpful when you want only one object, lazy initialisation (creation on first use) and global access are needed.
Singleton in the design pattern that states only one instance per jvm can be created (if implemented correctly).
DI(Dependency injection) is the design pattern that takes responsibility injecting dependency(inversion of control). Dependency can be singleton/prototype/scoped ... etc. Other than injecting dependency, DI patterns like spring DI also controlls lifecycle of bean.
Could someone explain what is the capi package used for? Is it for dependency injection?
Also what would be the proper way to connect two BOs (eg BasketBO and BucketBO to get access to their methods and create some new data) ?
Is it through the pipeline or through some new common object?
The capi (cartridge API) package is where you put the interfaces/classes to your public API of the cartridge. You might have noticed there is almost always an internal package too, this is where the implementation of the public API goes. So interface SomeObjectMgr will be in the com.example.capi package and the implementation class SomeObjectMgrImpl in the com.example.internal package. The capi package you can consider to be stable, while the internal packages can drastically change from version to version.
As for your second question, BO's are group together in an aggregate if they belong together, but an aggregate can refence other aggregates. So you are not limited in the relations you need to build . Example the BasketBO can access the BucketBO objects using its access methods. You could write an extension with business logic that manipulate the two BO's and return whatever data you need. However keep in mind that transaction control is on pipeline/pipelet level. So take that into account when designing your methods if you need to do a rollback of a transaction.
As for dependency injection, intershop uses google's guice framework. You can find more information on how to use it here.
I have this setup of component plus module, say FooComponent and FooModule, which provides a simple singleton, which needs to be replaced in one of the test variants. Therefore, in the variant I have instead FooTestComponent, which inherits FooComponent, but its #Modules annotation points to another module instead, FooTestModule. So far FooModule provides only one dependency, so no problem with that.
However, as dependencies that need not to be replaced in tests are added to FooModule, I see myself forced to replicate all of the methods to provide them in FooTestModule too since they can't be extracted to a parent abstract module that both FooModule and FooTestModule inherit from. What is the way to avoid this duplication?
The Dagger 2 User's Guide Testing Section contains advice for this very scenario.
To summarize the advice there:
Subclassing modules in order to swap in test doubles leads to the situation where you have to resolve all of the dependencies even if they are unused. Don't do this!
Instead of the approach in point 1, use different component configurations to achieve this: you can have a TestComponent that extends ProductionComponent and uses different modules that include bindings for test doubles
To achieve point 2, organize your modules for testability. This means considering modules as a collection of published and internal bindings and making sure you have a separate module for each published binding that has a 'reasonable alternative' i.e., an alternative you might like to replace with a test double that is not a mere internal dependency.
Alright well, so this is how it goes apparently: I'm really unsure this is the standard way of doing it, but deleting FooTestComponent and removing the annotations from FooTestModule allows FooTestModule to inherit from FooModule, and then you can instantiate FooTestModule where you override (but do not annotate) only the #Provides methods you need to mock.
I'm doing a small homemade project and I noticed that I wish to reuse a portion of code in other projects.
The conclusion is to move this code in a separate module and then publish it in my artifactory (I'm using maven) so it will become reusable.
The problem is that classes within my new module rely on each other. Usually, when I develop non-library project, I use Spring's inversion of control feature to resolve dependencies between the classes. But I can't use the dependency injection in my module, because the dependencies will be resolved only when bean is obtained from container.
Therefore, lets imagine the following situation:
I have Class1 in my module. It has field of type Class2, which should be.. lets say.. an instance of the same object always (i.e. singleton). My own ideas how to resolve it:
1) If Class2 doesn't contain any state, only methods (and plays an utility role) I can make it just static. Therefore I won't need to resolve this dependency, since I don't need to create it's instance anymore. But as a result, it can become really hard to test this type of class.
2) I can implement singleton pattern without using DI. The static Class2.getInstance() method could work, right?
3) I can forget about the idea of using singleton pattern and just create instance of Class2 with "new Class2()" expression (inline with field declaration or in Class1 constructor)
4) Somehow to use dependency injection so it could in a 'magic' way to inject my bean inside another one without using a container.
What is the best approach?
I have tried to understand AOP, Dependency Injection and Inversion of Control SPRING related concepts but I am having hard time understanding it.
Can anyone explain this in simple English ?
I understand your confusion and it took me some time to understand how these concepts were related together. So here is my (somehow personal) explanation of all this:
1. Inversion of Control
Inversion of control is a design principle rather generic that refers to the decoupling of the specification of a behavior from when it is actually executed. Compare for instance,
myDependency.doThis();
with
myDependency.onEventX += doThis();
In the latter, there is no direct invocation which is more flexible. In its general form, inversion of control relates to the observer pattern, events, or callbacks.
2. Dependency inversion
Dependency inversion is another design principle. Roughly speaking, it says that higher-level abstraction should not depend directly on lower-level abstractions; this results indeed in a design where higher-level abstraction can not be reused without the lower-level abstractions.
class MyHighLevelClass {
MyLowLevelClass dep = new MyLowLeverClass();
}
class App {
void main() { new HighLevelClass().doStuff(); }
}
Here, MyHighLevelClass can not compile without access to MyLowLevelClass. To break this coupling, we need to abstract the low level class with an interface, and remove the direct instantiation.
class MyLowLevelClass implements MyUsefulAbstraction { ... }
class MyHighLevelClass {
MyUsefulAbstraction dep;
MyHighLevelClass( MyUsefulAbstraction dep ) {
this.dep = dep;
}
}
class App {
void main() { new HighLevelClass( new LowLevelClass() ).doStuff(); }
}
Note that you don't need anything special like a container to enforce dependency inversion, which is a principle. A good reading is The Dependency Inversion Principle by Uncle Bob.
3. Dependency injection
Now comes dependency injection. To me dependency injection = IoC + dependency inversion:
dependencies are provided externally so we enforce the dependency inversion principle
the container sets the dependencies (not us) so we speak of inversion of control
In the example I provided above, dependency injection can be done if a container is used to instantiate objects and automatically inject the dependency in the constructor (we speak then frequently of DI container):
class App {
void main() { DI.getHighLevelObject().doStuff(); }
}
Note that there are various form of injections. Note also that under this perspective, setter injection can be seen as a form of callback -- the DI container creates the object then calls back the setter. The flow of control is effectively inverted.
4. AOP
Strictly speaking, AOP has little to do with the 3 previous points. The seminal paper on AOP is very generic and present the idea of weaving various sources together (possibly expressed with different languages) to produce a working software.
I won't expand more on AOP. What is important here, is that dependency injection and AOP do effectively plays nicely together because it makes the weaving very easy. If an IoC container and dependency injection is used to abstract away the instantiation of objects, the IoC container can easily be used to weave the aspects before injecting the dependencies. This would otherwise requires a special compilation or a special ClassLoader.
Hope this helps.
Dependency injection was explained very well in How to explain dependency injection to a 5-year-old?:
When you go and get things out of the
refrigerator for yourself, you can
cause problems. You might leave the
door open, you might get something
Mommy or Daddy doesn't want you to
have. You might even be looking for
something we don't even have or which
has expired.
What you should be doing is stating a
need, "I need something to drink with
lunch," and then we will make sure you
have something when you sit down to
eat.
AOP - Aspect Oriented Programming - basically means that the source you write is modified with other code, based on rules located ELSEWHERE. This means that you can e.g. say "as the first line of every method I want a 'log.debug("entering method()")' in a central place and each and every method you compile with that rule in place will then have that line included. The "aspect" is the name of looking on code in other ways than simply from first source line to last.
Inversion of Control basically means that you do not have a central piece of code controlling everything (like a giant switch in main()) but have a lot of pieces of code that "somehow" get called. The subject is discussed at Wikipedia: http://en.wikipedia.org/wiki/Inversion_of_control
These three are all different concepts, but they all work well together, and so Spring apps often make use of all of it at once. I'll give you an example.
Let's say that we have a web application that can do many different things. We could construct this application in many ways, but one way is to create a class that is in charge of doing each of these things. We need to invoke and create these classes from somewhere. One option is to have a big main class that creates one of each of these services, opens up a socket, and passes calls to these services as they come in. Unfortunately, we've gone and created ourselves a god class, which has way too much logic and knows way too much about how everything in our program works. If we change anything about our program, we're probably going to need to modify this class.
Also, it's difficult to test. We can't test any class in isolation if it runs around instantiating and invoking the other classes directly. Unit tests become much, much harder to write.
A way to get around this is to use inversion of control. We say "okay, these are service classes. Who instatiates them? Not me." Usually, each one defines an interface, like LoginService or BillingService. There might be more than one implementation of that interface, but your app doesn't care. It just knows that it can ask for a certain kind of a service or a service with a certain name, and it'll get something nice back.
Dependency injection allows us to wire all of our litle pieces together. Classes have accessible fields, constructor arguments, or setter methods that are references to the other components that they'll need to access. That makes unit testing much easier. You can create the object under test, throw a mock or stub dependency at it, and then test that the object behaved correctly in isolation.
Now, our real application is a complex jumble of pieces that all need to be wired together just so. There are many ways to accomplish this, including allowing the application to make guesses ("this class wants a UserService, there is exactly one other class I'm in charge of that implements UserService") or by carefully explaining how they wire together in XML or Java. Spring, at its core, is a service that takes care of wiring these classes together.
Now we get to AOP. Let us say that we have all of these classes that are wired to each other in elaborate ways. There are some cross-cutting concerns that we might want to describe in very generic ways. For instance, perhaps you'd like to start a database transaction whenever any service is invoked, and commit that transaction so long as the service doesn't throw an exception. It turns out that Spring is in a unique position to perform such a task. Spring can create proxy classes on the fly that implement whatever interface your classes need, and it can wrap your class in its proxy. Now, IoC and dependency injection certainly aren't necessary to do aspect-oriented programming, but it's an extremely convenient way to accomplish it.
The difference between Dependency Injection and Inversion of Control is explained very well in
http://martinfowler.com/articles/dipInTheWild.html
("You mean Dependency Inversion, Right?" section)
The summary:
DI is about how one object acquires a dependency. When a dependency
is provided externally, then the system is using DI.
IoC is about who initiates the call. If your code initiates a call,
it is not IoC, if the container/system/library calls back into code
that you provided it, is it IoC.
let me tell you some word about AOP, hope it make it simplier to understand.
The very base principle of AOP is finding common tasks/aspects which returns in
many places in the code and dont belong to the concerete business of the code. For example
write to log on every entrance to any function, or when an object is created wrapp it, or send email to admin when calling to specific function.
So instead of the programmers will handle these non businuss aspect we take it from them and
we manage these aspects behond the scene.
That all the basic of AOP on 1 leg....
A simple comparison from Spring in Action:
Whereas DI helps you decouple your application
objects from each other, AOP helps you decouple cross-cutting concerns from the
objects that they affect.