java - Spring 上下文作为运行时依赖

标签 java spring

我很困惑 this section Spring 文档。

For example, to create an application context and use dependency injection to configure an application, your Maven dependencies will look like this:

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.2.5.RELEASE</version>
        <scope>runtime</scope>
    </dependency> 
</dependencies>

Note the scope can be declared as runtime if you don’t need to compile against Spring APIs, which is typically the case for basic dependency injection use cases.

我知道 JSR 330(DI 注释)。但是如何与 ApplicationContext 类分离呢?如果你确实与它分离,为什么还要依赖 spring?

例如,quick start 是如何实现的?将 spring-context 作为运行时依赖项进行重写?或者“基本依赖注入(inject)用例”是什么?

最佳答案

我认为“基本用例”指的是基于 XML 的应用程序上下文。该文档说,如果您不在代码中直接使用 Spring 库,则不必将这些库包含在编译类路径中。 XML 配置就是这种情况,因为与 Spring 相关的所有内容都是在 XML 中配置的,因此不会被编译。

在您链接的快速入门中,作者正在使用基于注释的应用程序上下文配置,这需要在编译和运行时都包含 Spring 库。

示例 XML 配置: http://www.springbyexample.org/examples/intro-to-ioc-creating-a-spring-application.html

there should only be a few key points where the application code needs to directly access the IoC container [...]. If you're developing a web application, you may not need to directly access the IoC container at all since it will automatically handle instantiation of your controller and any beans it requires.

我并不完全熟悉它,但看起来您也可以像您建议的那样使用 JSR330 和 XML 配置来使用注释 Autowiring bean。 参见 here .这将允许使用注释,但不需要在编译时配置中包含 Spring。

关于java - Spring 上下文作为运行时依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35629734/

相关文章:

java - Android Canvas,具有不同缩放量的多个路径

java - IntelliJ 无法识别 "provided"的 Maven 依赖项

java - Spring Boot 多项目 Maven 应用程序上下文错误

java - 代表多个用户使用 OAuth2RestTemplate

java - 空闲标记 : freemarker. core.InvalidReferenceException

java - 如何在javafx中的同一窗口中打开新页面

Java算术表达式

java - Struts2:如何告诉我的 index.jsp 转发到 struts2 操作?

java - 计算加载 spring bean 所花费的时间

java - 无法为连接 URL postgres ://username:password@localhost:5432/dbname 创建类 'org.postgresql.Driver' 的 JDBC 驱动程序