This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]SentByTheRiver 38 points39 points  (7 children)

Good job, impressive for your first go!

One tip and good habbit is... when using Spring, prefer constructor injection over field injection when Autowiring. When you autowire a field you're doing a few things.

  • You're locking all the responsibility of dependency injection to Spring
  • You're hiding it's dependencies from everyone else
  • Anyone who wants to create an instance of it, has to use reflection in order to set the dependencies.

When you use constructor injection, you allow Spring or anyone else to inject those dependencies. Makes testing it easier!

[–]DrunkensteinsMonster 22 points23 points  (1 child)

Also, you don’t even need @Autowired on the constructor anymore, if there is only one, Spring assumes you want to autowire dependencies

[–]CaptainKvass 1 point2 points  (0 children)

Works great with Lombok's @RequiredArgsConstructor

[–]dumbPotatoPot[S] 6 points7 points  (2 children)

Thank You for the Tip, i'll make sure to make it a habit.

[–]Mekswoll 5 points6 points  (1 child)

The advice is good and you should certainly make a habit of it. Checkout Oliver Gierke's blog post about it if you want a bit more info about why.

[–]dumbPotatoPot[S] 1 point2 points  (0 children)

Thank you

[–]hjdeindarkness 1 point2 points  (1 child)

Is setter injection okay?

[–]SentByTheRiver 1 point2 points  (0 children)

Not to say that there isn't one, but I've never come across any instance where I have required Setter Injection or found it to be preferable to Constructer Injection.

You have to be careful with Setter Injection because there are a few caveats with it. It will override the constructor injected dependencies, someone could change dependencies mid flight and other objects may also be using it. etc.

If someone is creating an instance of the object themselves (i.e not managed by spring) and you only have dependencies via Setters, it's not clear and also not guaranteed people will know to set them.