spring自动装配有什么好处

Ami*_*aha 4 spring dependency-injection inversion-of-control autowired

自动装配是Spring的优势究竟是什么?

春季自动装配的一个例子是

public class TestClass {
    testMethod() {
        // .....
    };
}

public class MainClass {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClasspathXmlApplicationContext("test.xml");
        TestMethod obj = (TestClass) ctx.getBean("test");
        obj.testMethod();
    }
}
Run Code Online (Sandbox Code Playgroud)

测试文件

<bean id="test" class="TestClass">
Run Code Online (Sandbox Code Playgroud)

可以使用以下方法完成正常操作中的相同操作:

public class MainClass {
    public static void main(String[] args) {
        TestClass obj = new TestClass();
        obj.testMethod();
    } 
}
Run Code Online (Sandbox Code Playgroud)

Spring 的优势是什么,我的意思是我听说过控制反转和依赖注入这两个术语。在这两个示例中,通过newoerator再次通过 Spring XML 使用了一次 TestClass 引用。那么有人可以用简单的术语解释什么是优势。

f.t*_*ski 5

Spring 负责创建对象。假设在 Spring Boot 中你正在创建一个服务:

@Service
public class CreditService { ....
Run Code Online (Sandbox Code Playgroud)

有了这个,您对 spring boot 说他需要从 CreditService 类型创建一个对象,并且无论何时您想使用它,您都不需要创建它,您只需说:

@Autowired
private CreditService creditService;
Run Code Online (Sandbox Code Playgroud)

有了它,您将获得一个引用: creditService ,它将指向 spring boot 为您创建的对象并调用方法(服务)。所以基本上 spring 负责创建对象,你只是调用它,而不用担心在任何地方创建新对象。