Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Spring @PropertySource Annotation

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 341
    Comment on it

    Spring @PropertySource Example : Spring is a powerful framework, having almost everything a developer need to develop an application. Today we are going to talk about the @PropertySource annotation. Suppose we have a property file and we want to load and use the values in our Java class without using any IO method. So the question is how we can use property file values inside our Java class?

    The Spring Framework already has the answer of this question. @PropertySource annotation is used to load the property file inside the Java class. @PropertySource is mostly used with the conjunction of @Configuration. After passing the property file name in @PropertySource annotation we can use property file's values using org.springframework.core.env.Environment interface or @Value annotation.

    Example of @PropertySource annotation :

    application.properties

    # database configuration
    db.driverClassName=com.mysql.jdbc.Driver
    db.url=jdbc:mysql://localhost:3306/testdb
    db.username=root
    db.password=root
    

    Configuration.java

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.core.env.Environment;
    
    @Configuration
    @PropertySource("classpath:application.properties")
    public class Configuration {
        @Autowired
        Environment env;
        @Value("${db.url}")
        private String url;
        @Value("${db.driverClassName}")
        private String driverClassName
    
        @Bean
        public DatabaseConfig dbCon() {
            DatabaseConfig dbCon= new DatabaseConfig();
            dbCon.setDriverClassName(driverClassName);
            dbCon.setUrl(url);
            dbCon.setUsername(env.getProperty("db.username"));
            dbCon.setPassword(env.getProperty("db.password")); 
            return dbCon;
        }
    }
    

    In the above example we are getting passing the property file name application.properties in @PropertySource, and after loading this file all properties can be accessed using the env.getProperty(key) or using the @Value(${key}) annotation.

 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: