In my SpringMVC project I need a certain tactic to call a class which does parse a xml file which does own my RMI server ip & port & the url must be relative to servletContext url :
HttpServletRequest request;
request.getServletContext().getRealPath("/WEB-INF/LABLAB/RMI-Config.xml")
I want to load these classes when I start my application in tomcat not when I call a Controller Class because my application depend to my RMI so before anything else I have to parse my file & using the IP & PORT fields to start connecting to my RMI & then call the rmi method to do some stuffs later on ...
now
how I'm gonna do it ? please tell me how I can initialize an instance of HttpServletRequest & give an intial value when I'm not on the Controller classes as well .
Thank you
You are using Spring, then you can create a class and implement IntializingBean . If you want to get hold of ServletContext
you can simple use @Autowired
annotation in your initializing bean. For eg:
@Component
public class SomeBean implements InitializingBean {
@Autowired
private ServletContext context;
public void afterPropertiesSet() throws Exception {
String path = context.getRealPath("/WEB-INF/LABLAB/RMI-Config.xml");
//do something.
}
}
As per docs:
IntializingBean - Interface to be implemented by beans that need to react once all their properties have been set by a BeanFactory.
Or take a look here how to do this using ServletContextListener
.
You need to implement the ServletContextListener
interface and refer to it from your web.xml
:
<listener>
<listener-class>InitializingListener</listener-class>
</listener>
The interface has a contextInitialized(ServletContextEvent sce)
method, in which you can call sce.getServletContext()
, so you don't need a HttpServletRequest
.
If this doesn't work out, because you also need to access some of your Spring beans from the initializing class, then forget about implementing the ServletContextListener
interface, and do the following instead:
ServletContextAware
. This will cause Spring to inject the ServletContext
into your class. init-method
bean attribute, or define a @PostConstruct
annotated method) depends-on
bean attribute. As a result, the initialaizing bean will be created before any Controller bean. Without the last step, it cannot be guaranteed that your controllers won't start processing requests before the initialization bean finishes its work. However, specifying the depends-on
attribute on each and every controller bean is also problematic, especially that they are usually created by applying the @Controller
annotation instead of xml configuration. A nice workaround is described in this post .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.