I have situation like this. I cannot see any errors but I am not getting my results.
#ApplicationScoped
public class A {
private B b;
#Inject
public A(B b) {
this.b = b;
}
}
#Singleton
public class B {
private A a;
#Inject
public B(A a) {
this.a = a;
}
}
Is this type of dependency injection is wrong?
Can any one help me with this.
I'd avoid this circular dependency, there is a few reasons to do that.
Comment on this article
A messy constructor is a sign. It warns me that my class is becoming a monolith which is a jack of all trades and a master of none. In other words, a messy constructor is actually a good thing. If I feel that the constructor of a class is too messy, I know that it is time to do something about it.
And this one
You’ll find cases where a class A needs an instance of B and B needs an instance of A. This is a typical case of a circular dependency and is obviously bad. In my experience the solution is either to make B a part of A when the two are so strongly dependent that they really should be one class. More often though there is at least one more class C hiding in there so that B doesn’t need A but only C.
As Oliver Gerke commented:
Especially constructor injection actually prevents you from introducing cyclic dependencies. If you do introduce them you essentially make the two parties one because you cannot really change the one without risking to break the other, which in every case is a design smell.
Here is a small example of what I might do.
public class A {
private B b;
#Autowired
public A(B b) {
this.b = b;
}
public void doSomeWork() {
// WORK
}
public void doSomeWorkWithB() {
b.doSomeWork();
}
}
public class B {
private A a;
#Autowired
public B(A a) {
this.a = a;
}
public void doSomeWork() {
// WORK
}
public void doSomeWorkWithA() {
a.doSomeWork();
}
}
After refactoring it might look like this.
public class A {
private C c;
#Autowired
public A(C c) {
this.c = c;
}
public void doSomeWork() {
// WORK
}
public void doSomeWorkWithC() {
c.doSomeWorkThatWasOnA();
}
}
public class B {
private C c;
#Autowired
public B(C c) {
this.c = c;
}
public void doSomeWork() {
// WORK
}
public void doSomeWorkWithC() {
c.doSomeWorkThatWasOnB();
}
}
public class C {
public void doSomeWorkThatWasOnB() {
// WORK
}
public void doSomeWorkThatWasOnA() {
// WORK
}
}
Quoting from Section 5 of the CDI Specification 1.2:
The container is required to support circularities in the bean
dependency graph where at least one bean participating in every
circular chain of dependencies has a normal scope, as defined in
Normal scopes and pseudo-scopes. The container is not required to
support circular chains of dependencies where every bean participating
in the chain has a pseudo-scope.
ApplicationScoped is a normal scope, so this cycle should work.
In your sample, class A cannot be proxied since it's missing a zero-argument constructor. Adding this constructor (which may have protected or package visibility), your sample deploys without problems.
You can also use Setter based Dependency Injection to resolve this issue.
There is definitely a solution to this. Let me quote myself:
The right solution is to inject javax.enterprise.inject.Instance, where T is type of the class to be injected. Since the type is directly Foo, calling get() method on an object typed as Instance is guaranteed to inject the right object all the time. This approach works very well, because the instance is obtained dynamically from the container by the implementation itself and only as needed. Therefore, the responsibility of dependency retrieval is left to your code - your code is responsible not to make an endless loop.
#Named
public class Foo implements Fooable{
#Inject
private Instance<Foo> foo;
public void executeFirst(){
foo.get().executeSecond();
}
#Transactional
public void executeSecond(){
//do something
}
}
Related
I am working on an API which interface with a proprietary piece of hardware. In this API, I have constructed a utility class (for the sake of this post let's call it B), consisting of only static methods. Most of these methods depend on another class for communicating with the hardware, let's call this A. I am currently a little unsure how to design the dependency of B on A as I cannot instantiate B and inject the dependency using constructor injection. From a design perspective, what is the best way to model this behavior?
For a little more hands-on description, here is what I am trying to achieve. Let's say A has declarations of certain other classes like so
class A
{
private HardwareCommunicator communicator;
private ModelLoader modelLoader;
public HardwareCommunicator getCommunicator()
{
return communicator;
}
public ModelLoader getModelLoader()
{
return modelLoader;
}
}
And B then has static methods like so, which seek to use some of the members declared in A
class B
{
public static PerformOperation()
{
AnotherClass c = new AnotherClass();
c.someMethod(someValue, hardwareCommunicator.getCommunicator()); // Needs reference
}
}
Obviously, B needs a reference to A, so I am currently fiddling with passing the dependency as an argument to the method, like this:
class B
{
public static PerformOperation(HardwareCommunicator communicator) // Passed as argument
{
AnotherClass c = new AnotherClass();
c.someMethod(someValue, communicator.doSomething()); // OK, so far so good
}
}
Now I run into the problem that I sometimes need more dependecies than just the communicator in B, e.g. in another static method in B I might need both the HardwareCommunicator and the ModelLoader
class B
{
public static SomeOtherOperation(HardwareCommunicator communicator)
{
AnotherClass c = new AnotherClass();
c.SomeMethod(someValue, communicator.doSomething(),
ModelLoader.getModelLoader()); // Missing reference
}
}
OK, so I could just pass this as a parameter as well, but now I am thinking I have an architectural problem. I should (shouldn't I?) be able to just go
class B
{
public static SomeOtherOperation()
{
AnotherClass c = new AnotherClass();
c.someMethod(someValue, instanceOfA.getCommunicator(),
instanceOfA.getModelLoader());
}
}
Without being able to call a constructor on B and pass in an instance of A I obviously can't achieve this behavior.
What am I missing? Thank you.
(With static and dynamic I mean the distinction whether code is susceptible to change)
I have a bit of a weird problem I'm currently stuck on. I'm writing an application which involves some complex interactions between components in which it becomes hard to keep track of the code flow. To simplify this, I'm trying to structure the code by creating 'layers', where each layer has increased functionality compared to the layer above it. Each layer is contained in a package. I'm having the following problem:
Consider the following 2 classes and their subclasses with increased functionality:
Class A:
package layer;
class A {
B b;
A() {
b = new B();
}
void foo() {
b.foo();
}
/* More A-class methods here */
}
Class B:
package layer;
class B {
void foo() {
// Do something
}
/* More B-class methods here */
}
Subclass A:
package sublayer;
class ASub extends A {
ASub() {
super.b = new BSub(); // This needs a cast to compile
}
}
Subclass B:
package sublayer;
class BSub extends B {
#Override
void foo() {
// Do something with more functionality
}
}
In the end I just want to instantiate and modify classes ASub and BSub, being able to use all methods of superclasses A and B without actually needing to modify code in classes A and B itself.
If I call new ASub().foo(), I want the overridden foo() of BSub to execute instead of that of B. Ofcourse I can add a variable BSub bsub in ASub and override A's foo() method to call bsub.foo(), but this doesnt avoid the creation of the object b in the constructor of A, which seems sloppy coding. Any thoughts on this? Any comments are welcome.
Your question is a bit controversial. Object creation and dependency injection is the subject of a lot of discussion and a core focus of various frameworks and design patterns.
But here is, I hope, one simple answer to your question, which isn't a general "what's the best way to create objects in Java?"
In the code below, I move the responsibility of instantiating B to a method (instantiateB()) which is called from the A (superclass) constructor. So, when you want to subclass A, you override that method instead of overriding the constructor.
package com.matt.tester;
public class SE {
static class A {
B b;
A() {
instantiateB();
}
void instantiateB () {
this.b = new B();
}
void foo() {
b.foo();
}
/* More A-class methods here */
}
static class B {
void foo() {
System.out.println("Hellow from B.foo()!");
}
/* More B-class methods here */
}
static class ASub extends A {
#Override
void instantiateB() {
this.b = new BSub();
}
}
static class BSub extends B {
#Override
void foo() {
System.out.println("Hellow from BSub.foo()!");
}
}
public static void main(String[] args) {
A a = new ASub();
a.foo();
}
}
Using inheritance to promote reusability is a really really bad idea. The inheritance should be always driven by the nature of the objects that you are trying to describe. You need to learn yourself to work with terms and abstractions to ask yourself "What is the nature of what I am trying to describe". My suggestion is to learn a book on Domain Driven Design for example or Code Complete. Also think about polymorphism and design patterns.
In Java, what code to call a method in a singleton would be better practice, and why?
Please note that the following code is psudocode, not necessarily compilable code.
I ask this, as Method 2 (calling a method directly) is easier to implement in code, but not as often seen from my experience.
I'm developing for Android, but I suppose this question could apply to any Java program.
Something happens in class B. A method in Class A must be called.
Method 1: Interface registered in ClassA is called from ClassB
public class ClassA
{
// Member class B object
ClassB mClassBObject = new ClassB();
// Singleton has a private constructor
private ClassA(){}
public void onCreate() // Or main, or whatever method...
{
// Set callback for ClassB
mClassBObject.setOnSomethingHappened
(
new OnSomethingHappened()
{
public void callback()
{
// Do something in Class A called in Class B
}
}
);
}
}
public class ClassB
{
// Registered member callback
OnSomethingHappened mCallback;
// Interface for callback
public interface OnSomethingHappened()
{
public void callback();
}
// Method to set callback for this object
public void setOnSomethingHappened(OnSomethingHappened callback)
{
mCallback = callback;
}
// A method that invokes the callback in Class A
private void someMethod()
{
if (mCallback != null)
{
mCallback.callback();
}
}
}
Method 2: Calling a method directly from ClassA in ClassB
// We could also call a static method, but in this example, we are assuming a Singleton.
public class ClassA
{
// Reference to self
private static mSelf;
// Singleton has a private constructor
private ClassA(){}
public void onCreate() // Or main, etc
{
mSelf = this; // Store a reference to this Singleton class
}
public void someMethod()
{
// Do something in ClassA
}
public static getSelf()
{
return mSelf;
}
}
public class ClassB
{
// Code...
private void someMethodInClassB()
{
// Get ClassA to call
ClassA classAObject = ClassA.getSelf();
if (classAObject != null)
{
// Call method in ClassA
classAObject.someMethod();
}
}
}
It really depends on which way you want the dependency chain to go. I'm going to generalize the pattern I think you're trying to describe.
I'm the second example, B depends on A. As you mentioned, this is simpler, since what we're trying to setup is exactly that relationship.
In the first example, A depends on B. Technically this could be written so that A and B both depend on C (the callback mechanism). This kind of setup is popular as it reduces coupling between the components (A and B), allowing more flexibility for future changes.
The way you have written it doesn't quite capture this reduction of coupling in a "best practice" sort of way though... You'll find good examples where B represents a library or third party component, and A is your code. Clearly the library can't depend directly on your code, so this style of dependency inversion is used.
Provided that we have following classes:
public class B extends A{
#PostConstruct
public void setUp(){
a = new XYZ();
addListener();
}
}
public abstract class A{
X a;
public void addListener(){
a.addChangeListener();
}
}
In any implementation of class A there should be provided an initialization of 'a' property. Let's assume that each X implementations must override addChangeListener and that registering the listener is fundamental and necessary for each implementation of A. Is there a way to free developers of subsequent implementations of class A from remembering about this 'addListener' call each time and just put it somehow in A and forget about it? Thanks in advance.
I agree with #chrylis, use the #PostConstruct on A rather than each subclass of A. (Note the spec says only 1 method may be annotated in this manner.
Something like:
public interface X {
void addChangeListener();
}
public abstract class A {
X a;
protected abstract X newX();
protected void setUp() {}
#PostConstruct
public void init() {
a = newX();
a.addChangeListener();
setUp();
}
}
This allows forces the construction of the subclass, frees the implementors from remembering the addListener() call, while still allows them to perform class-specific initialization.
I think I'd take a different approach. Use the constructor to force the dependency to be met. Unless there's some reason why you have to use #PostConstruct, I think this will meet your needs.
public class B extends A{
public B() {
super(new XYZ());
}
}
public abstract class A{
X a;
public A(X a){
this.a = a;
a.addChangeListener();
}
}
Programmers extending A will be forced to pass in the initialization of a as a constructor parameter, so they can't forget -- the class will fail to compile if they don't do it. The constructor will always call the a.addChangeListener() method, and you know they can't skip out or override you because it's the constructor, and you don't need any annotations.
I have 2 questions, but they are about the same (similar?) problem.
First question:
public class A {
public void myProcedure() {
doSomethingA();
}
private void doSomethingA() {}
}
public class B extends A {
#Override
public void myProcedure() {
doSomethingB();
// IT DOESN'T CALL super.myProcedure
}
private void doSomethingB() {}
}
public class C extends B {
#Override
public void myProcedure() {
// I need to execute A's myProcedure here
}
}
How to run A's myProcedure, without setting doSomethingA to public?
Second question:
I create my own TextBox, there is a variable named myValue. Now I create an AdvancedTextBox that inherits TextBox, and AdvancedTextBox need to access myValue variable. The problem is, I want future developer using both TextBox and AdvancedTextBox, or inherit them can't access myValue. Is it possible?
EDIT: Oli Charlesworth and NullUserException ఠ_ఠ tell me to let C inherit A directly (first question). However, there's some cases this can be disaster. For example: A = TextBox, B = AdvancedTextBox, C = NumberAdvancedTextBox, if C inherits A, so C have to do everything that B does again, with some small changes.
How about this ...
Put A and C in the same package, and then put B in a different package.
Remove "private" from A.doSomethingA()
Give C an instance of A. ( Favor Composition Over Inheritance )
Since C and A are in the same package, C can call A.doSomethingA() anytime.
Here is definition of A
package ac;
public class A {
public void myProcedure() {
doSomethingA();
}
void doSomethingA() {}
}
Here is definition of B
package b;
public class B extends A {
#Override
public void myProcedure() {
doSomethingB();
// IT DOESN'T CALL super.myProcedure
}
private void doSomethingB() {}
}
Here is definition of C
package ac;
// do you really need to extend B?
public class C {
A a = new A();
public void myProcedure() {
a.doSomethingA();
}
}
Since doSomethingA is an implementation detail. I would change it from a private to protected to allow subclasses to call it directly.
If some outside module calls A.myProcedure, it is not necessary for doSomethingA to be public. The other module is not calling doSomethingA directly, and that's all that matters. The deliberate intention of Java scope modifiers is that they only apply when you call a function DIRECTLY, not indirectly via another function. This way a class can have a small number of public functions that define the public interface. This can be carefully documented and very stable. Then these public functions can call any number of private functions, and you can freely shuffle these private functions around, say to improve performance, or to work with a new environment, etc, without having to change the public interface.