0

I use a MongoConfiguration class to setup my Sping 4 MongoDB. I want to read properties from application.properties so I use @Value:

....
@Configuration
@EnableMongoRepositories
@ComponentScan(basePackageClasses = {Application.class})
public class MongoConfiguration extends AbstractMongoConfiguration {

   @Value("${mongodb.host}")
   String mongodb_host; 

   @Value("${mongodb.port}")
   int mongodb_port; 

   @Value("${mongodb.databasename}")
   String mongodb_databasename; 

   @Override
   protected String getDatabaseName() {
      return mongodb_databasename;
   }

   @Override
   public Mongo mongo() throws Exception {
      return new MongoClient( mongodb_host, mongodb_port );
   }

   @Override
   protected String getMappingBasePackage() {
      return "com.example.mongodb01";
   }
}

This works fine for a web application -- but when I try the same idea in a command line Java application it fails (it's as if the application.properties was found but @Value never ran). I know I am reading the applications.properties file OK. It must have something to do with the differences in running in a servlet container vs. an application but after much searching and trials I have not been able to resolve this and fix it. I would appreciate any help on this -- Thank you!

I did see a similar question and I tried adding the below to my MongoConfiguration but still had the same problem:

@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
  return new PropertySourcesPlaceholderConfigurer();
}

1 Answer 1

1

Did you include the @PropertySource

@Configuration
@PropertySource("classpath:application.properties")
@EnableMongoRepositories
@ComponentScan(basePackageClasses = {Application.class})
public class MongoConfiguration extends AbstractMongoConfiguration {
   ...
Sign up to request clarification or add additional context in comments.

2 Comments

Adding @PropertySource("classpath:application.properties") fixed it. It's interesting that it worked OK on the web app without PropertySource. So in the end I needed PropertySource and the Bean mentioned above for the non-web app but not for web apps.
I wonder if @Value is the best way to do this or if I should be using Environment env.getProperty() -- anyone with ideas on that please comment!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.