The core idea of Spring is summed up very well!

Author: Java program yuanhuanhuanhttps://blog.csdn.net/Lubanjava/article/details/100084602 Dependency injection is an ...

Author: Java program yuanhuanhuan
https://blog.csdn.net/Lubanjava/article/details/100084602

Dependency injection is an embodiment of face-to-face interface programming and the core idea of Spring. In fact, dependency injection is not an advanced technology, but it's a little mysterious to be packaged by Spring.

class Main { interface Language { void print(String s); } static class Java implements Language{ @Override public void print(String x) { System.out.println("System.out.print(\""+ x +"\")"); } } static class Coder { private Language lang = new Java(); public void helloWorld() { lang.print("hello world"); } } public static void main(String[] args) { Coder coder = new Coder(); coder.helloWorld(); } }

As shown in the code listing above, Coder uses the Java Language to print helloworld strings. Here, it not only depends on the Language interface, but also on Java classes, which makes it coupled with Java classes. It's easy to eliminate this dependency or decoupling.

interface Language { void print(String s); } static class Java implements Language{ @Override public void print(String x) { System.out.println("System.out.print(\\"\+ x +""\\")""); } } static class Coder { private Language lang; public void setLang(Language lang) { this.lang = lang; } public void helloWorld() { lang.print(""hello world""); } } public static void main(String\[\] args) { Coder coder = new Coder(); Language java = new Java(); coder.setLang(java); coder.helloWorld(); }

We have added the method of setting the specific Language to the Coder class

18 June 2020, 03:36 | Views: 8331

Add new comment

For adding a comment, please log in
or create account

0 comments