Reputation: 700
I want to start an embedded Tomcat server from a desktop application. The webapp that runs inside the Tomcat container is configured via Spring's WebApplicationInitializer (Right now I am simply extending AbstractAnnotationConfigDispatcherServletInitializer). How can I pass an already existing object from my desktop application to the WebApplicationContext used by the webapp ?
Here is some sample code that hopefully makes it more clear what I am trying to achieve:
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.
Upvotes: 0
Views: 270
Reputation: 4676
Using Jetty as my embedded container I was able to do this using ServletContext
attributes. By passing in the attributes when I create the WebAppContext
I'm able to access them in my beans by having them implement ServletContextAware
.
So I create my Jetty instance and set it up with a WebAppContext
:
WebAppContext webapp = new WebAppContext();
webapp.setAttribute("org.apache.geode.securityService", getSecurityService());
And then my bean simply implements ServletContextAware
:
public class LoginHandlerInterceptor implements ServletContextAware {
...
@Override
public void setServletContext(ServletContext servletContext) {
securityService = (SecurityService) servletContext.getAttribute("org.apache.geode.securityService");
}
}
I'm sure there must be a way to set servlet context attributes (not servlet init parameters) in Tomcat.
Upvotes: 0
Reputation: 2753
Spring container can manage all the ojects if it is initialized by Spring container. If you want any external object to be injected in spring on runtime you cannot do it.
So any object created by external coding cannot be managed or injected in spring.
Hope this clears your doubt.
Upvotes: 1