Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to load properties file and fetch values by using annotation in Spring

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 435
    Comment on it

    Properties file:

    It is basically used to store data that is constant and can be used anywhere in the program.

    Example: You can store the database credentials and connection parameters in the file and fetch it when required.

    How to use:

    PropertyPlaceholderConfigurer needs to be registered by the spring context to access the properties file. By adding the following snippet in the configuration file, bean registration is done automatically.

    < context:property-placeholder
      location="classpath:[file-name].properties"
      />

    Multiple properties file can also be included by adding the following:

    < context:property-placeholder
      location="classpath:[file1-name].properties,classpath:[file2-name].properties"
      />

    Property file needs to be in the same location of the other classes for using it this way.

    Using the properties:

    You can use the @Value annotation to fetch the values from the properties file.

    syntax:

    @Value("${property.value}")[access-specifier] [data-type] [field-name].

    This will fetch the property from the file and insert it into the particular field specified.

    Example:

    Suppose we have jdbc.properties file with the content:

    jdbc.username=root
    jdbc.password=root

    To get these values in the program we use the following steps:

    1) Adding the code snippet in the xml configuration file

    < context:property-placeholder
      location="classpath:jdbc.properties"
      />

    2) Using @Value :

    @Value("${jdbc.username}")private String userName;
    @Value("${jdbc.password}")private String password;

    userName and password will contain the values as 'root' as defined in the properties file.
    These values can be used throughout the program after following the above steps.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: