I found many examples about setter dependency injection for class member variables, but found it difficult to find any examples about setter dependency injection for local variables inside methods using spring.
How can I do this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Your given example of a SpellChecker being used by a TextEditor class could look like this before it is capable of Dependency Injection. You are creating a new instance of the class SpellChecker inside the method where you are using it.
If you want to decouple the code and be able to replace the SpellChecker by a mock for unit testing purposes or by another implementation provided by your Dependency Injection container you have to change the class and provide a field where this instance can be injected.
Since this is still not easy to test because you would need to use Reflection to inject a mock into that private field you can provide a Setter or make the field package visible by removing the modifier private from the field. So a unit test in the same package can access this field and provide the mock.