Spring @RefreshScope с @Configuration не обновляется динамически - PullRequest
0 голосов
/ 29 апреля 2020

Я использую весеннюю загрузочную версию (2.2.5.RELEASE) и весенние облачные зависимости (Hoxton.SR3).

У меня есть класс, как показано ниже:

    @RefreshScope
    @Configuration
    public class JavaMailConfig {


    @Value("${email.common.config.host:ERROR: Could not load email config host}")
    private String host;

    @Value("${email.common.config.port:ERROR: Could not load email config port}")
    private String port;

    @Value("${email.common.config.transport.protocol:ERROR: Could not load email config protocol}")
    private String protocol;

    @Value("${email.common.config.username:ERROR: Could not load email config username}")
    private String mailUserName;

    @Value("${email.common.config.password:ERROR: Could not load email config passsword}")
    private String mailPassword;

    @Value("${email.common.config.password:ERROR: Could not load email config smtpAuth}")
    private String smtpAuth;

    @Value("${email.common.config.password:ERROR: Could not load email config startTlsEnable}")
    private String startTlsEnable;

    @Value("${email.common.config.password:ERROR: Could not load email config sslTrust}")
    private String sslTrust;

    @Bean
    public JavaMailSender getJavaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(host);
        CommonUtility.setPort(mailSender, port);

        mailSender.setUsername(mailUserName);
        mailSender.setPassword(mailPassword);

        Properties props = mailSender.getJavaMailProperties();

        props.put("mail.transport.protocol", protocol);

        props.put("mail.smtp.auth", smtpAuth);
        props.put("mail.smtp.starttls.enable", startTlsEnable);
        props.put("mail.smtp.ssl.trust", sslTrust);

        return mailSender;
    }

}

Я использую конфигурацию Spring Cloud для получения информации от git. В том же проекте у меня есть класс ниже:

@RestController
@RefreshScope
@RequestMapping("/email")

public class EmailController {



    private static final Logger LOG = LoggerFactory.getLogger(EmailController.class);

        @Autowired
        SendMailService sendMailService;



        @Value("${email.common.config.username:ERROR: Could not load email config username}")
        private String mailUserName;



        @PostMapping(value = "/sendMail")
        //Note:Not to remove @RequestBody and @RequestBody as swagger UI will not interpret it correctly
        public ResponseEntity<String> sendMail(@RequestBody  EmailRequestDto emailRequestDto) {

            if (checkAllEmailAddValid(emailRequestDto)) {

                System.out.println("mailUserName from controller " + mailUserName);
                System.out.println("profile " + profile);
                sendMailService.sendEmail(emailRequestDto);

                LOG.debug("Send mail completed successfully ");
                return new ResponseEntity<>("Mail has been sent successfully", HttpStatus.OK);
            } else {
                LOG.error("Email addresse provided is  invalid");
                return new ResponseEntity<>("Email address provided is  invalid", HttpStatus.BAD_REQUEST);
            }

        }

Когда я обновляем sh URL-адрес с помощью "actator / refre sh", restcontroller обновляется успешно, но не класс @Configuration, как указано ранее. .

Обновление: класс ниже, который я использую JavaMailSender:

@Component
@RefreshScope
public class SendMailServiceImpl implements SendMailService {

    private static final Logger LOG = LoggerFactory.getLogger(SendMailServiceImpl.class);

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * {@inheritDoc}
     */
    @Override
    public void sendEmail(EmailRequestDto emailRequestDto) {
....
}

Так можно ли использовать refre sh область видимости аннотации конфигурации?

Спасибо заранее за любой совет

1 Ответ

0 голосов
/ 30 апреля 2020

На всякий случай, если у кого-то есть эта проблема, мне удается заставить ее работать, но я не знаю, правильно ли она, хотя.

Я добавил аннотацию ConfigurationProperties с префиксом, который содержит ключ моего файла свойств поверх аннотации моего компонента:

 @ConfigurationProperties(prefix = "email.common.config")
  @Bean
    public JavaMailSender getJavaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(host);
        CommonUtility.setPort(mailSender, port);

        mailSender.setUsername(mailUserName);
        mailSender.setPassword(mailPassword);

        Properties props = mailSender.getJavaMailProperties();

        props.put("mail.transport.protocol", protocol);

        props.put("mail.smtp.auth", smtpAuth);
        props.put("mail.smtp.starttls.enable", startTlsEnable);
        props.put("mail.smtp.ssl.trust", sslTrust);

        return mailSender;
    }
...