1
首先,我们来谈谈DI。
来自Spring Doc的备注,
依赖管理和依赖注入是不同的东西。
- 依赖管理是“组装所有需要的库(jar 文件),并在运行时将它们放到您的类路径中,也可能在编译时”。
- 依赖注入是,假设您想在您的类中创建一个
Service 对象,而不是使用service = new Service(); 创建它,而是让spring 框架处理该bean 的生命周期。
依赖管理示例:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
</dependencies>
这样你的项目中就有了所有这些 jar 文件。
spring-context-4.2.5.RELEASE.jar
spring-aop-4.2.5.RELEASE.jar
spring-beans-4.2.5.RELEASE.jar
spring-core-4.2.5.RELEASE.jar
依赖注入示例:
在您的quick-start 示例中,您使用构造函数注入将MessageService 注入MessagePrinter。您没有在任何地方创建MessageService。 Spring 容器为您创建它。
@Component
public class MessagePrinter {
final private MessageService service;
@Autowired
public MessagePrinter(MessageService service) {
this.service = service;
}
public void printMessage() {
System.out.println(this.service.getMessage());
}
}
@Configuration
@ComponentScan
public class Application {
@Bean
MessageService mockMessageService() {
return new MessageService() {
public String getMessage() {
return "Hello World!";
}
};
}
...
}
2
现在我们来谈谈transitive dependency and run-time dependency。
传递依赖
这意味着发现您自己的依赖项所需的库并自动包含它们。
例如,如果您在 pom.xml 中指定了依赖项 A 和 B。 A 依赖于 C、D。B 依赖于 E。您无需在配置中包含 C、D、E。
由于传递依赖,C、D、E 会被自动包含进来。
运行时依赖
限制传递依赖是依赖作用域的一种。
"这个范围表示不需要依赖
编译,但用于执行。它在运行时和测试中
类路径,但不是编译类路径。”
3
现在的问题是:对于 DI,是否存在“不需要针对 Spring API 进行编译”的情况,而是可以将范围设置为运行时?类似问题here.
是的,我能想到的一个例子是 Web 应用程序。假设我正在使用带有 Spring 插件的 Strtuts。 (以下示例来自 Manning 的“Struts 2 in Action”)
我想告诉 Spring 创建一个 Login 类的实例,用作请求的操作对象。
向web.xml添加一个spring web context listener
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
定义一个名为springManagedLoginAction的bean Login in
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="portfolioService" class="manning.chapterNine.utils.PortfolioServiceJPAImpl"/>
<bean id="springManagedLoginAction" class="manning.chapterNine.Login" scope="prototype">
<property name="portfolioService" ref="portfolioService"/>
</bean>
</beans>
在struts-config-login.xml的动作类中使用这个bean
<action name="Login" class="springManagedLoginAction">
<result type="redirectAction">
<param name="actionName">AdminPortfolio</param>
<param name="namespace">/chapterEight/secure</param>
</result>
<result name="input">/chapterEight/Login.jsp</result>
</action>