Spring's profile usage comparison and application scenario analysis

Source: Internet
Author: User

There is a feature in spring that uses profile to select different configurations in different environments, and plainly, by setting a parameter to choose to use different data, the data may be a bean, an XML file, or a propertes file.

After the code walkthrough and testing, I generally know what this feature is for, but also initially know how it is implemented, but in fact I still do not quite understand the advantages and benefits of it, because according to their previous project experience, I think in this way seems to be a little bit of complexity of the simple function.
It's just that I've seen it on the web more than once, and it seems like a lot of people are using it. So I think it's good to know, to learn, maybe it's just that I don't know for a moment, and it doesn't mean that the benefit doesn't exist.
In order to let the new contact of friends to better understand, I basically here is the code and test are written out, and three ways to simple contrast, so that in the need to use the specific circumstances of the specific choice of the scene.

Implementation Method One

With full Java code Annotated, first create a simple class with a constructor method and a Get, set method:

package springtest4; Public  class  profiletest {private     String msg; public  profiletest  (String msg)        {super ();    this . msg = msg; } public  String getmsg  () {return  msg; } public  void  SETMSG     (String msg) {this . msg = msg; } public  void   Printtest  () {system.    Out . println (msg); }}

Then create a class that is equivalent to the XML configuration file in spring, and use annotations to declare the class as a configuration class, while declaring the upper class as a bean and setting the profile name (that is, the selection parameter of the profile above):

  PackageSpringTest4;ImportOrg.springframework.context.annotation.Bean;ImportOrg.springframework.context.annotation.Configuration;ImportOrg.springframework.context.annotation.Profile;@Configuration  Public  class profileconf { @Bean @Profile("Test1") PublicProfiletestProTest1() {return NewProfiletest ("test11111"); }@Bean @Profile("Test2") PublicProfiletestProTest2() {return NewProfiletest ("test22222"); } }

The @configuration here declares that this class is a configuration class equivalent to XML in spring, and that the remaining two are said in the previous text description and are not mentioned.
As for the explanation of this code, I want to explain it by following the test code that is called below, and the main method of simulating the profile call is as follows:

Package SpringTest4;import org. Springframework. Context. Annotation. Annotationconfigapplicationcontext;public class Mainpro {public static void main (string[] args) {Annotationconfigapplicationcontext context = new Annotationconfigapplicationcontext ();Context. Getenvironment(). Setactiveprofiles("Test2");Context. Register(profileconf. Class);Context. Refresh();String mstring = Context. Getbean(Profiletest. Class). getmsg();System. out. println(mstring);Context. Close();}}

Here the new Annotationconfigapplicationcontext () declares an empty context, and I want to learn that spring should not have to be explained.
Context.getenvironment (). Setactiveprofiles ("test2") means acquiring an environment variable, or understanding it to get the configuration data, and then setting the parameter or name of the active profile to test2.
Context.register (Profileconf.class) registers the specific configuration file, here is Profilecon.class.
Then the next few lines of code are refreshing the context, get the specific Bean object, and so on, these are more general operations.
Results after the above method execution

And when I put Context.getenvironment () setactiveprofiles ("Test2") here the Test2 is set to test1, the result becomes test11111.
So the combination of the above profileconf code, I think it is easier to understand, that is, when the profile is configured here, when we set Activeprofiles as a parameter, Spring will invoke the content of the profile corresponding to this parameter when it is loaded.

But why should I say I don't see the benefits of this use? Because I think in this case, it is possible to create a new object directly with different parameters of the constructor method.
Of course, this is just an example to illustrate this feature, the actual use of nature is not so, when actually used, may be used to load different configuration files in the values and attributes, may also be used to invoke a different configuration file.
But even so, I still feel that can be implemented in the way of parameters, it seems that there is no need to wrap around, and do not see how to simplify the development, nor see any performance improvement.

Then there is the way to achieve two

This approach is similar to the one above, because the only difference is that the Java class that real deal the XML configuration file becomes the XML configuration, because the class that uses the constructor method and the Get, set method is the same, so it is no longer repeated, and here is the beginning of the Test1.xml:

<?xml version= "1.0" encoding= "UTF-8"?>  <beans xmlns="Http://www.springframework.org/schema/beans"xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="Http://www.springframework.org/schema/beans http://www.springframework.org/ Schema/beans/spring-beans.xsd ">              <beans profile ="Test1">  <bean id="ProTest1" class="Springtest4.profiletest" >   <constructor-arg name="msg" value="test11111" />  </Bean></Beans><beans profile ="Test2">  <bean id="ProTest2" class="Springtest4.profiletest" >   <constructor-arg name="msg" value="test22222" />  </Bean></Beans></Beans>

This is also a very simple spring configuration, except for the necessary files to the tail, there are only two almost identical beans, specifying the profile name, as well as an internal common bean, the bean is injected with the constructor function.
For this notation, the invocation is basically the same, except that the context gets the XML instead of the CALSS:

Package SpringTest4;import org. Springframework. Context. Support. Classpathxmlapplicationcontext;public class Mainpro {public static void main (string[] args) {Classpathxmlapplicationcontext context = new Cla Sspathxmlapplicationcontext ("Test1.xml");Context. Getenvironment(). Setactiveprofiles("Test2");Context. Refresh();String mstring = Context. Getbean(Profiletest. Class). getmsg();System. out. println(mstring);Context. Close();}}

As for the specific instructions here, I would like to explain the first example, there should be no need to say more.

Implementation Method Three

The first two ways, fundamentally, change the way the profile is declared, and here it needs to be called, the top two of the details are called in the Java class, And here is the call in Web. XML, of course, since there is a Web. xml file, it is natural to be a website project only, the XML file is configured as follows:

<! DOCTYPE Web-app Public "-//sun Microsystems, INC.//DTD Web Application 2.3//en" "Http://java.sun.com/dtd/web-app_2_3. DTD "><web-app>  <display-name>Archetype Created Web Application</display-name>  <servlet>     <servlet-name>Dispatcher</servlet-name>      <servlet-class>Org.springframework.web.servlet.DispatcherServlet</servlet-class>     <init-param>        <param-name>Contextconfiglocation</param-name>        <param-value>Classpath:test1.xml</param-value>      </init-param>       <init-param>        <param-name>Spring.profiles.default</param-name>        <param-value>Test2</param-value>      </init-param>      <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>      <servlet-name>Dispatcher</servlet-name>      <url-pattern>/</url-pattern>    </servlet-mapping>></Web-app>

This web. XML is also a file only to illustrate profile, as long as a selvlet configuration, two Init-param, the first is to specify a custom dispatcher-servlet.xml, if not specified, the following error occurs when booting Tomcat:

org.springframework.beans.factory.BeanDefinitionStoreException:IOException parsing XML document from ServletContext resource [/web-inf/dispatcher-servlet. XML]; nested exception is java.io.FileNotFoundException:Could not open ServletContext resource [/web-inf/ Dispatcher-servlet.xml]at org. Springframework. Beans. Factory. XML. Xmlbeandefinitionreader. Loadbeandefinitions(Xmlbeandefinitionreader. Java:343) at Org. Springframework. Beans. Factory. XML. Xmlbeandefinitionreader. Loadbeandefinitions(Xmlbeandefinitionreader. Java:303) at Org. Springframework. Beans. Factory. Support. Abstractbeandefinitionreader. Loadbeandefinitions(Abstractbeandefinitionreader. Java: the)

The

and the second init-param is the name of the specified default profile.
in order to test whether this is possible, I made a slight modification on the basis of the second approach, adding a Init-method method to the Java class, and the corresponding Java class and XML configuration following the modification:

package springtest4; Public  class  profiletest {private     String msg; public  profiletest  (String msg)        {super ();    this . msg = msg; } public  String getmsg  () {return  msg; } public  void  SETMSG     (String msg) {this . msg = msg; } public  void   Printtest  () {system.    Out . println (msg); }}
<?xml version= "1.0" encoding= "UTF-8"?>  <beans xmlns="Http://www.springframework.org/schema/beans"xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="Http://www.springframework.org/schema/beans http://www.springframework.org/ Schema/beans/spring-beans.xsd ">              <beans profile ="Test1">  <bean id="ProTest1" class="Springtest4.profiletest " Init-method="Printtest">   <constructor-arg name="msg" value="test11111" />   </Bean></Beans><beans profile ="Test2">  <bean id="ProTest2" class="Springtest4.profiletest " Init-method="Printtest">   <constructor-arg name="msg" value="test22222" />   </Bean></Beans></Beans>

In the process of starting Tomcat, the console also prints out the expected data, proving that the third approach is also feasible.

The above is I know of three kinds of profile implementation, as for the specific application scenario, although I know the main purpose is to facilitate a variety of different environments to switch. such as the production of a set of configurations, testing a set of configurations, such as a single-machine environment, a set of cluster environment and so on, but I think it can be deployed at the time, in the spring Context:property-placeholder and import resource when the switch.
And this kind of switch is more easy to get started than profile, so it is not clear where the advantages of profile are, welcome friends to leave a message.

Spring's profile usage comparison and application scenario analysis

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.