title: How to reload configuration bean with properties from database
body: <p>I need to create a spring javamail bean initialized with values from database for each mail sent. Based on this article, <a href="http://www.opencodez.com/java/how-to-load-application-properties-from-database.htm" rel="nofollow noreferrer">How to Load Application Properties from Database</a></p>
  
  <p>I've configured my <code>PropertyPlaceholderConfigurer</code> to load values from both properties file and database. I have the following bean(<code>mailSender</code>) in my java configuration class for sending mail from my application which loads host, port, username and password from the database,</p>
  
  <pre><code>@Configuration
  public class MailSenderConfig {
      @Bean
      public JavaMailSender mailSender() {
          JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
          javaMailSender.setHost(PropertiesUtils.getProperty("mail.server.host"));
          javaMailSender.setPort(Integer.parseInt(PropertiesUtils.getProperty("mail.server.port")));
          javaMailSender.setUsername(PropertiesUtils.getProperty("mail.server.username"));
          javaMailSender.setPassword(PropertiesUtils.getProperty("mail.server.password"));
          return javaMailSender;
      }
  }
  </code></pre>
  
  <p>But my problem is when the database values changes the <code>mailSender</code> bean has the old values which is provided while starting the application context. For any changes to take place to the bean I need to restart the server for updating the bean values.</p>
  
  <p>I inject this bean in my controller where I need to send a mail like this,</p>
  
  <pre><code>@Autowired
  private JavaMailSender mailSender;
  </code></pre>
  
  <p>Based on some suggestion, I tried to use <code>@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)</code> but it din't create a new bean definition(still has old values). </p>
  
  <p>So what I need is, every time a mail is sent using this <code>mailSender</code> bean it should pick the values from database without restarting the context or server. Is it possible or how it can be done? </p>
  
  <p>Any help is appreciated. Thanks.</p>
  
  <p>Similar question: <a href="https://stackoverflow.com/questions/39094419/spring-refresh-a-bean-created-from-code-reading-a-database">Spring: Refresh a bean created from code reading a database</a></p>