Advanced configuration of the Spring MVC framework

Source: Internet
Author: User
Tags define definition commit include new features postgresql string access
Advanced This article will provide you with the configuration tips for the Spring MVC framework to help manage multiple instances of a spring-based Web application. This configuration management topic is often overlooked by academics, but this is especially important for real-world web development. This topic does not directly relate to any specific technology, so we will start with the most basic concepts to illustrate this issue. Below, we will provide a range of solutions for projects based on this technology, based on the Spring MVC framework.

   Spring Configuration

People often configure a Web application on more than one host. For example, in production, a Web site may have only one instance. In addition to this instance, developers can configure additional (development) instances on the machine for development. You can also benefit from maintaining other application appliances on a local development server within your organization. The purpose of this example is to enable Web designers to obtain quality-assured material and to provide access to people who need to provide file information for their applications.

As you all know, even the simplest scenario requires three instances to be installed, configured, and maintained. For teams in different geographic locations, it is more difficult to do such a project. For any Web application project that is not particularly simple, a number of developers are required to install the project appliance and local settings, as well as the appliances that run unit tests.

Many organizations have developed their own products as Web applications. We can find this in many products, such as e-commerce systems, Content management Systems (CMS), and blog publishing platforms. This type of product can be deployed on multiple servers. For successful multipurpose Web applications, their developers must ensure that their applications are easy to install and integrate seamlessly with other Web applications. After this discussion, it should be clear that the application configuration that is the subject of this article is one of the most important issues that a common Web application project developer needs to address.

Version control systems such as CVS or Subversion are a standard tool used by development organizations. This tool represents the central source version Library of some organizations that are used to keep the source code in order. Users can track changes in the source code of the application, display differences between versions, and identify project branches. Also, they make it possible to make partial updates in an application deployment.

Obviously, the version control system software is necessary to track source code, and it is very helpful for solving application configuration problems. In this article, we will not focus on the version control system, because there are already a lot of related materials. Here, we'll look at one small topic in versioning issues: how to make Web applications more convenient to configure (especially Web applications written with the Spring MVC framework).

The question is: What kind of configuration are we talking about here? Any Web application requires resources that are typically specific to the server to which it is running, such as database URLs, SMTP servers that send e-mail, and folders that contain proprietary software files. Such settings should be centralized, making the application configuration simpler.

However, this is only the simplest version of the problem. Sometimes, more complex configurations are required in application development. This means that the different beans in each deployment must be connected, which complicates the problem.

The solutions to these application configuration problems have many advantages, including simplifying the installation and configuration of your application, making source code versioning easier, and reducing the conflict in the source code version library. Below, we will discuss this topic in detail.

Problem

Let's begin by demonstrating the simplest version mentioned above. In this scenario, we want to change the simple configuration parameters in the application deployment, such as links, passwords, and so on. If you have ever developed a Web application using the Spring MVC framework, you should know the two profiles that will be used here:
    • /web-inf/applicationcontext.xml, which allows you to configure the bean, or to display the application context. With this file, you can define your own business logic beans, resources, and any other beans that can be associated with the Web port.
    • /web-inf/[Servlet-name]-servlet.xml, which is used to configure the required beans in the WEB layer, view parser, controller, validator, and all other MVC frameworks. [Servlet-name] refers to the name of the Spring dispatcher servlet defined in the Web.xml deployment descriptor.

So where's the problem? The problem is that a host-specific bean definition will be included in Applicationcontext.xml. One of the most obvious examples is the bean that contains the JDBC connection information, but there are more than 10 similar beans in any slightly more complex application. Take a look at the following example:

<bean id= "DataSource"
class= "Org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name= "Driverclassname" >
<value>org.postgresql.Driver</value>
</property>
<property name= "url" >
<value>jdbc:postgresql://localhost/test</value>
</property>
<property name= "username" >
<value>postgres</value>
</property>
<property name= "Password" >
<value></value>
</property>
</bean>


The problem with the solution is the maintenance of the Applicationcontext.xml file. For starters, imagine that the project is placed in a source code version control system, such as CVS. Below, suppose you want to add new features to your Web site, you need to add additional bean definitions to the application context definition. The problem is how to manifest these changes on the production server.

Typically, the local instance of the application does not use the same database as the active site, so the Applicationcontext.xml file will include settings that give you access to the local database. When you want to commit changes in the source code version library, you need to be aware of these host-specific synchronization features. The files in the version library may eventually use the configuration in the local settings. If you want to update the configuration on the production server, you must manually synchronize the values of these properties. It's a tedious task, and it's very easy to make mistakes.

This issue is even more important for each instance of the application. If three developers are using a code snippet base address, and they are using a local database. When you commit the changes, each of them must be very cautious when updating the source code on the local server. They will manually synchronize these changes and then submit their work. As a result, version control systems are no longer useful for these configuration files. If you've ever used spring MVC, you should know that Applicationcontext.xml is a key component in your application because it glues everything together. So it's important that we need a mechanism to help keep the items in the application in order.

As mentioned earlier, this is a simpler configuration problem that you might encounter. The more difficult problem is now when you need to make different bean connections in different servers. This kind of problem often occurs in the Daily software development task. For example, if your product has a Customer authentication module, you can authenticate users from a relational database or LDAP server. Naturally, this authentication module can be configured with a bean that abstracts a particular version of the library. If you want to change the way users are validated in different application deployments, you need to make different bean connections in the Applicationcontext.xml file. This configuration issue is common to all applications that have configurable features in the deployment.

In the following, we will discuss both of these configuration issues. First we will focus on the problem of synchronized bean properties and their solutions, and then we'll discuss more complex synchronization bean connectivity issues.

   Solution

   Synchronizing Bean Properties

One possible solution to this problem is to put all host-specific parameters into the normal Java properties file, using the spring Propertyplaceholderconfigurer class to write these parameters to the bean properties.

Using this solution, we can generate the following properties file (/web-inf/jdbc.properties):

Jdbc.driver=org.postgresql.driver
Jdbc.url=jdbc:postgresql://localhost/test
Jdbc.user=postgres
jdbc.password=
Our bean configuration is as follows:

<bean id= "Propertyconfigurer"
class= "Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
<property name= "Location" >
<value>/WEB-INF/jdbc.properties</value>
</property>
</bean>

<bean id= "DataSource"
class= "Org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name= "Driverclassname" >
<value>${jdbc.driver}</value>
</property>
<property name= "url" >
<value>${jdbc.url}</value>
</property>
<property name= "username" >
<value>${jdbc.user}</value>
</property>
<property name= "Password" >
<value>${jdbc.password}</value>
</property>
</bean>
As mentioned above, we define an instance of the Propertyplaceholderconfigurer class and set its Location property to our property file. This class is implemented as a post processor for the Bean factory and replaces all placeholders (${...} with the attributes defined in the file). Value).

With this technology, we can remove all host-specific configuration properties from Applicationcontext.xml. In this way, we are free to add new beans to the file without worrying about the synchronization of host properties. This can simplify production deployment and maintenance.

   Synchronous Connection

The above technique solves the first problem, but if you plan to modify the bean connections between different application deployments, this technique is not appropriate. One solution to this problem is to create an extra one called applicationcontext-[hostname]An XML definition file for the. Xml. which[hostname]is the name of the host that deployed the application. For example, on a local machine, this file is usually named applicationcontext-localhost. XML, while at deployment, it may be renamed to applicationcontext-somehost.com. Xml.

It can be guessed that this file must include all configuration beans that are specific to a host. In this article, we will assume that the DataSource bean definition will be in such a file, rather than a generic applicationcontext.xml definition. Of course, this mechanism is not in conflict with the former, but in order to be simpler and clearer, we will only focus on this approach.

Now that we have a specific configuration, let's discuss how to integrate it into the entire spring MVC configuration concept. There are many ways to achieve this, and we will explain them in detail. But first, we should note that since some beans may be in separate configuration files, all local references to them must be replaced with global names in Applicationcontext.xml.

For example, refer to the following:

<property name= "Someproperty" >
<ref local= "Somebean"/>
</property>
Should be changed to:

<property name= "Someproperty" >
<ref bean= "Somebean"/>
</property>
After that, we have a lot of ways to add additional resources to the configuration. One of the most obvious is the use of <import> tags to include this additional resource in the Applicationcontext.xml configuration file. When used, place the label at the beginning of the Applicationcontext.xml file. For example:

<import resource= "Applicationcontext-somehost.com.xml"/>

All common bean definitions in a standalone XML definition file and in a generic application context definition file now have host-specific connections. Since most beans are not host-specific, we can process applicationcontext.xml files as freely as other resources in the Web application, and we can synchronize them with the appropriate version control system.

However, the above methods also have some drawbacks. If you want to keep different configurations of different XML files, you still have to worry about Applicationcontext.xml synchronization because the names of the resources must be changed according to the different servers. Although it's a lot better than the original solution, just change the file name, but it still requires the developer's manual assistance.

Because the host configuration does not need to be changed so frequently compared to applicationcontext.xml, the next step is to move the host configuration to the Web.xml file (if possible). Luckily, we have an available solution. Take a look at the following fragment about the Web.xml configuration:

<listener>
<listener-class>
Org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/web-inf/applicationcontext.xml
/web-inf/applicationcontext-somehost.com.xml
</param-value>
</context-param>
As you can see, in addition to the common Contextloaderlistener in the Web.xml file, we have also added the contextconfiglocation context parameter configuration. This parameter is used to indicate where the framework looks for these configuration files. If this argument is omitted, spring can only be found in Applicationcontext.xml. Here we also define a host-specific configuration file to use.

With this approach, we remove all host-specific configurations from the Applicationcontext.xml file, which eases their synchronization in different application deployments.

If this approach becomes your new habit, you can also make it more flexible. You can also remove host-specific configuration from the Web.xml file by complying with the following directives.

To do this, you need to create a class that is specific to our application context:

Package net.nighttale.spring.util;

Import java.net.InetAddress;

Import Org.springframework.web.context.support.XmlWebApplicationContext;

public class Perhostxmlwebapplicationcontext
Extends Xmlwebapplicationcontext {

Protected string[] Getdefaultconfiglocations () {
String hostname = "localhost";
try {
hostname = Inetaddress.getlocalhost (). GetHostName ();
catch (Exception e) {
}

String perhostconfiguration = Default_config_location_prefix
+ "applicationcontext-"
+ hostname
+ Default_config_location_suffix
;

Logger.debug (
"Adding per host configuration file:"
+ perhostconfiguration
);

if (GetNamespace ()!= null) {
return new string[] {
Default_config_location_prefix
+ GetNamespace ()
+ Default_config_location_suffix
, perhostconfiguration};
}
else {
return new string[] {
Default_config_location
, perhostconfiguration};
}
}
}
This class expands the xmlwebapplicationcontext that is often used as the default value in spring. The Xmlwebapplicationcontext class copies the configuration of the Web application from the XML definition file. By default, it can be configured from Applicationcontext.xml and[Servlet-name]-servlet.xml the application in the file. The only one by one additional tasks that this class performs is to get the host name it resides in and to applicationcontext-[hostname]The. xml file is added to the configuration file list.

To use this class, we need to compile it, include it in the class path, and instruct the spring framework to use it. The first two steps are very simple and we will not repeat them here. We can instruct sping to use it by Contextclass context parameters. In addition to the original configuration in the Web.xml file, we can add the following:

<context-param>
<param-name>contextClass</param-name>
<param-value>
Net.nighttale.spring.util.PerHostXmlWebApplicationContext
</param-value>
</context-param>
If we use this configuration fragment, there will be three files that are used to initialize the framework:[Servlet-name]-servlet.xml, applicationcontext-[hostname]. xml and Applicationcontext.xml.

As you can see, the Applicationcontext.xml and web.xml files are completely free of any specific configuration details, and you don't have to worry about destroying the configuration when you update your application.

However, there is a shortage of this approach. Because, whether or not it is used, you need a third configuration file in your application deployment. In this case, no host-specific configuration is required. For example:

<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE beans Public "-//spring//dtd bean//en"
"Http://www.springframework.org/dtd/spring-beans.dtd" >

<beans></beans>
Finally, you need to know the specific host name that the application context class needs to find. The easiest way to check the host name is to run the following code on the machine:

System.out.println (Inetaddress.getlocalhost (). GetHostName ())
It can be executed as Java code, or as a script with Java-style syntax in a script language like BeanShell or groovy that you prefer to use. After you have obtained the name of the host, you should create a default/web-inf/applicationcontext-[hostname]. Xml empty folder (as we defined above), and then we can start.

   Concluding remarks

In this article, we provide a series of configuration tips that make it easier to do your daily work with the Spring MVC framework. If you want to know how to maintain a variety of Web application deployments, try to find the solution that best suits your development process. Your life will be much easier.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.