0

I am new to Spring and I want to start using dependency injection.

I have many classes, and they hold dependencies as interfaces references, which I populate with objects I send as parameters to the constructor.

I know I can configure each class separately to inject each dependency with a specific implementation, but that means if I want to change the implementation of a specific dependency to all classes then I need to change every class, I want to be able to do that in one place for all classes.

What is the best way to do that?

2
  • 1
    I don't quite understand. Normally you just change your bean in one place and it gets injected everywhere. Why do you need to change anything in classes which get your bean injected? Would probably be good if you post some code to illustrate your question. Commented Jan 12, 2017 at 11:59
  • For example if i have an interface for notification in multiple classes across the application, and i have EmailNotification implementation but now I wrote SMSNotification and I want to use that instead. Commented Jan 12, 2017 at 14:20

1 Answer 1

1

In your class you will inject the interface:

public class Foo {

  @Autowried
  private Boo boo;
}

Then you will control which implantation gets added to the spring container :

@Service
public class BooImpl implements Boo {

}

Now all you need to do is change the implementation.

If possible I would use Spring Boot, you can download the examples and run the straight away https://spring.io/guides/gs/spring-boot/

Sign up to request clarification or add additional context in comments.

2 Comments

Can someone also add the beans.xml that I need to write for this?
@GiladBaruchian I've updated my answer, look at the Spring Boot examples.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.