Automatically load custom properties files when Java Web project starts

Source: Internet
Author: User

First create a class
public class Contextinitlistener implements Servletcontextlistener
Makes the Class A listener. Used to listen to the entire container life cycle, primarily initialized and destroyed.

After the class is created, add a simple listener configuration to the Web. XML configuration file, which is the class that we just defined.
XML code

<Listener>  <!--Lang:xml -    <Description>Servletcontextlistener</Description>  <!--Lang:xml -    <Listener-class>Com.test.web.filter.ContextInitListener</Listener-class>  <!--Lang:xml -</Listener>  

After configuring the listener, we begin to write Contextinitlistener code. The implementation of the interface will automatically generate two methods, initialization and destruction, we just paste this bar, another useless. Web projects Generally, the relative path is generally in web-inf/classes, get the file under the path, preferably with GetClass (). getResourceAsStream ("/baseconfig.properties");

Java code

  @Override  public  void   Contextinitialized (Servletcontextevent sce) {Properties props           = new   Properties ();          InputStream InputStream  = null   try   {InputStream  = GetClass              (). getResourceAsStream ("/baseconfig.properties" );              Props.load (InputStream);          String TempPath  = (string) props.get ("path" );  catch   (IOException ex) {Ex.print          StackTrace (); }      }  

Transferred from: http://my.oschina.net/u/585275/blog/109227

Automatically load custom properties files when Java Web project starts

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.