Tell me how to use Soring DI in Java using a constructor. For example interface Enimal.java

public interfase Enimal(){ void say(); } 

And there are 2 implementations of this interface: Cat.java & Dog.java:

 public class Cat implement Enimal{ public void say(){ System.out.println("Say myau"); } } public class Dog implement Enimal{ public void say(){ System.out.println("Say gav"); } } 

And there is a Service for working with higher classes:

 public class ModelService{ private Enimal enimal; public ModelService(Enimal enimal){ this.enimal = enimal; } public void saySomething(){ enumal.say(); } } 

How can I create a ModelService object each time with passing different objects? For example, now I need to use the Cat class, and then I need to use Dog?

  • It's not entirely clear what you mean. Spring is a framework, not a language. Java syntax is used to call methods and constructors. - not a Programmer
  • @not a Programmer just trying to learn the spring, for this is not quite understand everything. For example, I create an object from a context, using the getBean method, a configuration using annotations, the class has a constructor with parameters, how can I create an object from the context and pass parameters to this constructor? - Main Star
  • If this is an object that you receive from the context, then you do not need to call the constructor (Spring does it for you) - not a Programmer
  • @notaProgrammer OK, but what if you need to create this object with a constructor, only transfer parameters to the dynamic constructor (for example, if there is an interface, and 2 implementations of this interface), then how can I create it with different implementations every time? - Main Star
  • Please give an example so that I clearly understand what you mean. - not a programmer

1 answer 1

 @Configuration public class AppConfig { // Обьявляем бин с типом Enimal и id - "enimal" (из названия метода) @Bean public Enimal enimal() { Enimal enimal = new Cat(): // Если нужно использовать Dog // Enimal enimal = new Dog(): return enimal; } // Обьявляем бин ModelService, чтобы Spring смог внедрить в него бин с типом Enimal (если используете Spring Boot это не нужно) @Bean public ModelService modelService(Enimal enimal /*получаем бин enimal из контекста*/) { return new ModelService(enimal); } } 
  • that is, for each implementation of this constructor, with each of the classes that implement the Enimal interface, it is necessary to create a separate configuration class, right? And I also wanted to ask, can you suggest some kind of project on the Github opensource, so that you can gain experience with SpringFramework? - Main Star
  • No, you can add as many bins as you want in one configuration file. Read better Spring in Action, a great book. - not a Programmer