How to automatically install in the spring container (such as applicationContext.xml) when the server starts

If you want to automatically load the spring container when the server starts, it must be configured in web.xml. So how to configure it? Please see the code below

The first:

Without any parameters, load the spring container directly through the listener. At this time, the default reading path is to read WEB-INF/applicationContext.xml, which means that there can only be one configuration file of the spring container and the name must be applicationContext.xml

 

<!-- This listener is used to automatically load spring's ApplicationContext-->
<listener>

	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

 The second:

 

Manually specify parameters, change the default read path, and allow multiple files to be read to form a spring container. In the following case, applicationContext1.xml and applicationContext2.xml can be read.

<context-param>
	
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/applicationContext*.xml</param-value>
	
</context-param>

<!-- This listener is used to automatically load spring's ApplicationContext-->
<listener>

	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

 

So how to use the spring container on the server side? If it is an Action, you only need to define the same property as the id of the bean in the spring container on the Action, and the action will be automatically assembled. If it is a servlet, then how to do it? Please see the following code:

private ApplicationContext context;


//When spring is integrated with Servlet, because Servlet and Filter cannot be automatically assembled, the init() method of Servlet should be used for manual assignment.
	@SuppressWarnings("unchecked")
	@Override
	public  void init() throws ServletException
	{
		//The hibernateTemplate object is still obtained from the spring container because the connection between the server and the database is a
		context=WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
		ht=(HibernateTemplate)context.getBean("ht");
		
		hibernateTrans=(UserDaoInterface)context.getBean("hibernateTrans");
		
	};

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326666824&siteId=291194637