java - 如何将现有对象传递给 Spring WebApplicationContext?

标签 java spring spring-mvc

我想从桌面应用程序启动嵌入式 Tomcat 服务器。在 Tomcat 容器内运行的 web 应用程序是通过 Spring 的 WebApplicationInitializer 配置的(现在我只是扩展 AbstractAnnotationConfigDispatcherServletInitializer)。如何将已有的对象从桌面应用程序传递到 web 应用程序使用的 WebApplicationContext ?

这里是一些示例代码,希望可以更清楚地说明我想要实现的目标:

public class MyWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { SpringAppConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { SpringWebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

@Configuration
@EnableWebMvc
public class SpringWebConfig extends WebMvcConfigurerAdapter {
}

//somewhere in my desktop application where I want to start the server...
    MyObject myObj = new MyObject(SomeParameters params); 
    //I want to have myObj available for Spring managed objects,
    //like @Components and @RestController etc. that get created by Spring

    Tomcat tc = new Tomcat();
    //some tomcat configuration here
    tc.start(); //automatically searches for WebApplicationInitializer in classpath
    //I do not know how the Spring managed beans can be made aware of myObj.

最佳答案

Spring容器可以管理所有由Spring容器初始化的对象。如果你想在运行时在 spring 中注入(inject)任何外部对象,你不能这样做。

因此任何由外部编码创建的对象都无法在 spring 中进行管理或注入(inject)。

希望这能消除您的疑虑。

关于java - 如何将现有对象传递给 Spring WebApplicationContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41802621/

相关文章:

java - Hibernate @OneToOne 和 ConstraintViolationException 关系的一侧

java - 无法在 IntelliJ 中构建 Spring RestService 教程

java - 从 Spring 访问 EJB 类

java - spring mvc 中图片未上传

java - RandomAccessFile 读取 Jar 文件中的文件

java - 为什么这个流不返回任何元素?

java - 矩形二维数组中所有元素的总和

java - null != null - 关于如何重新安排代码或防止这种情况的任何想法?

java - Hibernate 不会自己创建 Join Table

java - 来自 Spring JSP 的常量引用列表