Read file properties using Spring annotations

前端 未结 2 2003
终归单人心
终归单人心 2021-01-02 08:46

I\'m trying to learn how to read properties file using spring. After an internet searching I found that I can use @value and @PropertySource annota

相关标签:
2条回答
  • 2021-01-02 09:00

    I can see several issues in the code.

    1) Your place holders for values should be in the form ${mogodb.url}, not #{mongodb.url}. The "#" has a different meaning (See Spring Expressions).

    2) You are going to need a PropertySourcesPlaceholderConfigurer bean to do the injection of the values

    3) Sooner or later you are going to have a number of Beans floating around, and in I would use @ComponentScan to allow the context to know these without you having to mention them one by one

    4) If you use ComponentScan to get the beans, you are going to have to provide AppConfigMongoDB bean once

    I end up with these classes after doing all that:

    Main.java

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class Main {
    
    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        AppConfigMongoDB mongo = applicationContext.getBean(AppConfigMongoDB.class);
        System.out.println("db= "+mongo.getMongoDb());
        System.out.println("URL= "+mongo.getMongoDbUrl());
      }
    }
    

    SpringConfiguration.java

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
    
    @Configuration
    @ComponentScan
    public class SpringConfiguration {
    
      @Bean
      public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
      }
    }
    

    AppConfigMongoDB.java

    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    
    @Configuration
    @PropertySource("classpath:config/config.properties")
    public class AppConfigMongoDB {
    
      @Value("${mongodb.url}")
      private String mongodbUrl;
    
      @Value("${mongodb.db}")
      private String defaultDb;
    
      public String getMongoDb() {
        return defaultDb;
      }
    
      public String getMongoDbUrl() {
        return mongodbUrl;
      }
    }
    
    0 讨论(0)
  • 2021-01-02 09:18

    Nice reply given by @Ian Sparkes . Adding some of my inputs here. Configuring the PropertySourcesPlaceholderConfigurer is not mandatory. I am able to get the value from my properties file and set it to the filed variable of my main Configuration class without it.

    There is also another way to get the values of your keys in the properties file. Use org.springframework.core.env.Environment class . This class automatically loads all the key-value pairs in properties file that is in class path.

    Example :

    @Configuration
    @ComponentScan(basePackages="com.easy.buy")
    @PropertySource({"classpath:config.properties","classpath:props/db-${env}-config.properties", 
    	"classpath:props/app-${env}-config.properties"})
    public class CatalogServiceConfiguration {
    	Logger logger = LoggerFactory.getLogger(CatalogServiceConfiguration.class);
    	
    	//This object loads & holds all the properties in it as key-pair values
    	@Autowired
    	private Environment env;
    	
    	/**
    	 * Instantiate the DataSource bean & initialize it with db connection properties
    	 * @return
    	 */
    	@Bean(name="basicDataSource")
    	public BasicDataSource basicDataSource() {
    		String dbUrl = env.getProperty("db.url");
    		String dbUser = env.getProperty("db.user");
    		String dbPwd = env.getProperty("db.pwd");
    		String driver = env.getProperty("db.driver");
    		
    		logger.info("Initializing CatalogServiceConfiguration");
    		logger.info("dbUrl=" + dbUrl);
    		
    		BasicDataSource ds = new BasicDataSource();
    		ds.setDriverClassName(driver);
    		ds.setUrl(dbUrl);
    		ds.setUsername(dbUser);
    		ds.setPassword(dbPwd);
    		
    		return ds;
    	}
    }

    0 讨论(0)
提交回复
热议问题