简体   繁体   中英

Run in development mode in web project

I have a Spring MVC Project based on maven build tool. In my application, I have to make web-service calls to external server for some data. I have implemented it and it all works well.

But in the development mode, I would rather want to avoid them. So currently I have

public static boolean devel = false

I use above boolean with if else statements so that if under development mode, then provide static data. If not development mode then make web-service calls.

But I find this boolean declaration dirty. In the sense that, I manually have to correct the boolean in my code every time I deploy it in production. And once I forgot to that causing havoc.

Is there any decent way? I would not like to have this variable declared in the code but from some constant obtained during build process or probably some VM argument. Or they might even be a better way. If so, how I incorporate it in my spring-maven project.

What I would do is have code default to production behavior so something like, have the bool devel comes from a properties file. The default value in the classpath = false and and in order to override it I would use something like:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="ignoreResourceNotFound" value="true"/>
    <property name="locations">
        <list>
            <value>classpath:config.properties</value>
            <value>${external-config}</value>
        </list>
    </property>
</bean>

on my dev machine I run my application with

-Dexternal-config=file:/c:/debug.properties

that properties file holds some placeholder that overrides values stored in config.properties located in the jar/war

What I would consider a "decent way" (as you term it) is to use dependency injection ; using either Spring or Java CDI features. This is exactly the type of scenario, that dependency injection is useful for.

You would then declare an interface, which is implemented by two different classes:

  1. the real class - that connects to the remote server, and
  2. a development/test class that returns static data.

Your launch configuration would then determine which of the two classes gets injected into your application.

Spring (3.1+) supplies a way to specify a @Profile, which can be used in conjunction with @Configuration annotations. Have a look at http://spring.io/blog/2011/02/14/spring-3-1-m1-introducing-profile/

Using that methology, you can create your own configuration beans per environment (production, development, staging, etc)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM