In Java like this:
#Injected
private Int a;
#Injected
private Int b;
public void myMethod() {
System.out.println(a);
System.out.println(b);
}
I have no idea how to test this method.
I do not recommend you to write code like this and if it is already written to refactor it. The idea of dependency injection is to have dependencies which can be injected runtime. At the moment they are injected by reflection so as davidxx says you have to use reflection to set values which you need . This may cause you a lot of headaches.
Instead of using field injection like this :
#Inject
private Int b;
You can use setter injection like this :
#Inject
public void setB(int b) {
this.b = b
}
Another way is to use constructor injection like this:
public YourClass {
private int a;
private int b;
#Inject
public YourClass(int a, int b){
this.a = a;
this.b = b;
}
}
Assuming what you meant is to use #Inject (from javax.inject), then you could use #InjectMocks from Mockito, though this probably won't work too well with primitive values (assuming you meant to write int rather than Int).
There are some caveats to using this, however: https://tedvinke.wordpress.com/2014/02/13/mockito-why-you-should-not-use-injectmocks-annotation-to-autowire-fields/
How to test methods which using private parameters without
getters(Injected)?
Only with reflection as you don't have direct way to set these fields.
You can do this at hand or with tool such PowerMock.
The WhiteBox class allows to achieve it.
Now, I don't advise this way.
It is tricky and dependencies of the component should be visible to make them clear and to also allow them to be naturally switchable and testable.
You are not forced to use setters.
You could use a constructor injection.
#Inject
public Foo(Int a, Int b) {
this.a = a;
this.b = b;
}
It is a little more verbose but it is really not a big deal.
Related
I'm a beginner in Java programming and I'm having some problems to understand some concepts. I would like to know if both implementations are the same:
Code 1
public class MyThisTest {
private int a;
public MyThisTest(int a) {
this.a = a;
}
Code 2
public class MyThisTest {
private int a;
public MyThisTest(int b) {
a = b;
}
Yes, both are the same, let's see why:
First
public class MyThisTest {
private int a;
public MyThisTest(int a) {
this.a = a;
}
You are using this to refer the member variable a. The use of this is because by parameter there is another a variable. If you don't use this what variable will be assigned the value? The same as the parameter, so it doesn't take effect because it is 'auto-assign' the value.
Word this ensures tthe member variable is referenced. This is mostly used in constructors and getter/setters because the parameter name should be the same as the member variable name, so to handle the ambiguity this is used.
The second code
public class MyThisTest {
private int a;
public MyThisTest(int b) {
a = b;
}
Into constructor there is no ambiguity between variables, so this is not needed, but you can still use this and it works perfectly.
Yes both implementations are same. But I would highly recommend you to read about it in detail so that you don't make any future mistake. This answer goes in detail about when we should use this.
this keyword would be added by compiler.
Actually, if you write something like this
public class A {
private int a;
public A(int b) {
a = b;
}
}
Compile and then decompile it you can see the work of compiler
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
public class A {
private int a;
public A(int b) {
this.a = b;
}
}
So, i would say avoiding this is just a usage of some syntax sugar.
For example I have:
public abstract class SomeAbstract {
private int a;
private int b;
..
private int z;
}
public class A extends SomeAbstract {
private String aField;
}
public class B extends SomeAbstract {
private long bField;
}
(default constructors/setters/getters are omitted)
I have some instance of a class A and i wanna create
instance of a class B from A(abstract fields).
Yes, I can use abstract class constructor or create constructor for class B like this :
public B(A a) {
this.a = a.getA();
this.b = a.getB();
..
this.z = a.getZ();
}
But since I have many fields this does not look nice and convenient
Is there another way?
You can create a constructor in the super class that receives another super class.
public abstract class SomeAbstract {
/* attributes... */
public SomeAbstract() {
}
protected SomeAbstract(SomeAbstract another) {
this.a = another.a;
/* and on... */
}
}
And reuse this constructor in sub classes:
public class B extends SomeAbstract {
public B(A a) {
super(a);
this.specificAttribute = a.somethingElse;
}
}
If you have that many fields and don't want/need to create the whole code manually, you can use an external library that helps you with the mapping between classes. Some options are:
Dozer that maps data between objects. The configuration can be done through XML or annotations. This library works (AFAIK) using reflection, so it may have a direct impact on the performance of your application.
Orika that generates byte code at runtime to map data between objects. The configuration is done at design time. This library works (AFAIK) using reflection, so it may have a direct impact on the performance of your application, when I tested it, the execution time was faster than Dozer (about 7x faster).
MapStruct that will generate code to map the classes (using getters and setters, validating nulls and on) and this code will be available for at runtime. The configuration is done at design time through annotations. This library works (AFAIK) using Java code, so it's similar to the normal execution of the code (e.g. execute b.setValue(a.getValue())).
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
}
}
In the doJob() method, B is referenced through getter. I personally do not favor this idea and would prefer just b.execute() since I know for sure that getB() will never be modified.
I know that by doing this, would be moving away from encapsulation, but isn't encapsulating B object an overkill here?
class A{
private B b;
public void setB(B b){
this.b = b;
}
public B getB(){
return b;
}
public void doJob(){
getB().execute();
}
}
It really doesn't matter if you access B through its attribute or getter as long as the attribute remains private (so yes, calling getB() is an overkill, it certainly doesn't break any design pattern).
In this scenario it's probably overkill because it's a simple object. But what if there was lazy loading and your object looked like this..
class A{
private B b;
public void setB(B b){
this.b = b;
}
public B getB(){
this.b = this.b ?? new B();
return this.b;
}
public void doJob(){
getB().execute();
}
}
Then it's not overkill to access your private members via a property.
I don't know if this will help you, but if B is a dependency then your object should be setup like this where IB is the interface of the concrete object B. It's an inversion of control pattern to decouple the concrete object B from A. But this is overkill for simple object graphs as well
class A{
private IB b;
// Use inversion of control
public A(IB b){
this.b = b;
}
public IB getB(){
return this.b;
}
public void doJob(){
getB().execute();
}
}
You are minimizing risk by using the getter. What if it turns out the B was null in one use case or you need to initialize B because of a new requirement. This pattern allows you to update getB() without having to change anything else in A.
public B getB(){
if(b == null) {
b = getEntityManger().findB(); // or wherever you wanted to get B from
}
return b;
}
Providing accessor/mutator methods for a private member enables you to add error checking, change the storage of the member, and do other things internal to the class. How you access the member within the class is your choice.
If you discover you need to change the class internals later, then switching to the accessor/mutator can be done then. Certainly this simple example does not require the accessor (getter) method. But realize that a more complex case might benefit by using the getter.
That is ok only if you make the whole class, or at least make the setter and getter, final.
Otherwise this breaks:
class A2 extends A {
private B2 b;
#override
public void setB(B b){
this.b = new B2(b);
}
#override
public B getB(){
return b.toB();
}
}
Now calling the non-overriden doJob() will use wrong member variable.
I was trying to understand how hibernate work in the sense that how putting #Entity on a class makes it a persistent class ?
i.e
#Entity
class A{
private int b;
public int getB(){
return b;
}
public void setB(int b){
this.b = b;
}
}
behaves like below written class at runtime
class A{
private int b;
public int getB(){
return (SQL code to fetch b from DB)
}
public void setB(int b){
(SQL code to set b in DB)(b);
}
}
If we say it is using reflection then how it is changing the code that is inside the methods ?
Hibernate proxied / runtime-weave your class. Meaning when other classes invoke methods of your class, it doesn't invoke it directly, but it invokes the proxy. This proxy then contains logic that involves persistence context operations.
Have a look at library such as cglib or aspectj if you want to delve deeper in this topic (not necessarily the ones used by hibernate)