0

I use @Autowired annotation like this:

@Autowired
private MyService1 myService1;

@Autowired
private MyService2 myService2;

But new Intellij IDE 2016(3) suggests and proposes to replace:

private final MyService1 myService1;
private final MyService2 myService2;;

@Autowired
public MyClass(MyService1 myService1, MyService2 myService2) {
    this.myService1= myService1;
    this.myService2= myService2;
}

Tell me what is the difference and what is right?

Vinay Veluri
  • 6,671
  • 5
  • 32
  • 56
user5620472
  • 2,722
  • 8
  • 44
  • 97
  • 1
    Possible duplicate of [Setter DI vs. Constructor DI in Spring?](http://stackoverflow.com/questions/7779509/setter-di-vs-constructor-di-in-spring) – Jesper Nov 30 '16 at 09:40

3 Answers3

1

Both approaches are correct.

From docs

Spring included, provide a mechanism for ensuring that all dependencies are defined when you use Setter Injection, but by using Constructor Injection, you assert the requirement for the dependency in a container-agnostic manner"

@Autowire at constructor level guarantees that you will have all the required dependencies when your spring container finally creates your bean for that class.

Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
1

It is suggecting to using constructor inject instead of Setter inject. For nomal use, there is no big different.

We usually advise people to use constructor injection for all mandatory collaborators and setter injection for all other properties. Again, constructor injection ensures all mandatory properties have been satisfied, and it is simply not possible to instantiate an object in an invalid state (not having passed its collaborators). In other words, when using constructor injection you do not have to use a dedicated mechanism to ensure required properties are set (other than normal Java mechanisms).

Here is an article to explain it Setter injection versus constructor injection and the use of @Required

Also you can get quite a lot question/answer in stackoverflow. Setter DI vs. Constructor DI in Spring?

Community
  • 1
  • 1
Liping Huang
  • 4,378
  • 4
  • 29
  • 46
0

Yes, it is used correctly. This is called the Constructor Injection.

Constructor Injection allows you to use the final modifiers of your choice and to easily pass your own not managed by Spring objects (mocks, for example).

If you are not forced to using field injection, choose constructor injection.

Grzegorz Piwowarek
  • 13,172
  • 8
  • 62
  • 93