-1

I have modifiers such as protected, private and private transient. I am using manual wiring. I need to use setter injection. Which all variables do I need to wire?

Mohit Kanwar
  • 2,962
  • 7
  • 39
  • 59
lifeat stake
  • 65
  • 1
  • 9

2 Answers2

1

This depends on YOUR needs, not on the needs of Spring.

Because you have setters, then I recommend to make the variables private.

transient would only be taken in account when you serialize this class (the call it must implement the Serializabe interface), but this is highly unusual, so I would not add transisient as long as the class is not Serializabe

Ralph
  • 118,862
  • 56
  • 287
  • 383
0

Dependency Injection is a software design pattern that implements inversion of control for resolving dependencies. Dependency injection means giving an object its instance variables.

It's like making the class independent of the implementation details of other services (e.g.) that it uses.

e.g.

public class MyClass{
private OtherService os = new OtherServiceImpl();
  ...
}

In the above code, MyClass is dependent upon OtherServiceImpl. Let's say, in future we realize that OtherServiceImpl does not suffice all of our requirements, or there is another service MuchBetterServiceImpl which is provided by different vendor which helps us.

Now, if we modify MyClass to use MuchBetterServiceImpl as

private OtherService os = new MuchBetterServiceImpl();

We would need to re-comiple and re-test MyClass again.

But with coming in of Autowiring and mocking tools we can make MyClass independent of implementation details of OtherService.

public class MyClass{
@Autowired
private OtherService os ;
  ...
}

For your particular case, this can be achieved as public class MyClass{

private OtherService os ;
public OtherService getOs(){
 return os;
}
@Autowired
public void setOd(OtherService pOs){
 os=pOs;
}
  ...
}

Whatever way is it done Setter/Constructor it is providing de-coupling the two classes.

Now, to spring it does not matter if you are autowiring what type of fields. As the responsibility of spring is to find a suitable implementation and plug it in your class.

Spring uses reflection to do this linking. And setters should be public/accessible.

It doesn't matter what is the access modifier of your field. refer this and this questions. for more details.

Coming to your question: What variables do you need to wire: Preferably all the services, controllers, Daos or any other components that you need to decouple should be auto wired.

Community
  • 1
  • 1
Mohit Kanwar
  • 2,962
  • 7
  • 39
  • 59