Источник собственности не получает автопроводку - PullRequest
1 голос
/ 15 марта 2020

Я по каким-то причинам использую источники внешних свойств. Один из источников внешних свойств не получает автосвязь, получая нулевой указатель при создании bean-компонента authenticantionion

Сообщение об ошибке

Причина: org. springframework.beans.BeanInstantiationException: не удалось создать экземпляр [com.filechecker.check.Authenticator]: конструктор сгенерировал исключение; вложенное исключение: java .lang.NullPointerException

Причина: java .lang.NullPointerException: null at com.filechecker.check.Authenticator. (Аутентификатор. java: 30) ~ [классы! /:0.0.1-SNAPSHOT]

Строка № 30:

    String username = emailPropertyConfig.getEmailConfig().getUsername();

не работает один

@Component
@PropertySource(value="${email.app.properties}",ignoreResourceNotFound = false)
@ConfigurationProperties
public class PropertyEmailConfiguration {

    private EmailConfig emailConfig =  new EmailConfig();

    public EmailConfig getEmailConfig() {
        return emailConfig;
    }

    public void setEmailConfig(EmailConfig emailConfig) {
        this.emailConfig = emailConfig;
    }
}


@Component
public class Authenticator extends javax.mail.Authenticator {

    @Autowired
    PropertyEmailConfiguration emailPropertyConfig;

    @Autowired
    CipherCrypt cipherCrypt;

    private PasswordAuthentication authentication;

    public Authenticator() throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException {

        String username = emailPropertyConfig.getEmailConfig().getUsername();
        String password = cipherCrypt.decrypt(emailPropertyConfig.getEmailConfig().getEncryptPassword());
        authentication = new PasswordAuthentication(username, password);
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return authentication;
    }
}

работает один

@Component
@PropertySource(value="${external.app.properties}", ignoreResourceNotFound = true)
@ConfigurationProperties
public class PropertyConfiguration {

    private List<FileStructureConfig> fileStructureConfig = new ArrayList();

    private List<EmailSendingProperties> emailSendingProperties  = new ArrayList();

    public List<FileStructureConfig> getFileStructureConfig() {
        return fileStructureConfig;
    }

    public void setFileStructureConfig(List<FileStructureConfig> fileStructureConfig) {
        this.fileStructureConfig = fileStructureConfig;
    }

    public List<EmailSendingProperties> getEmailSendingProperties() {
        return emailSendingProperties;
    }

    public void setEmailSendingProperties(List<EmailSendingProperties> emailSendingProperties) {
        this.emailSendingProperties = emailSendingProperties;
    }


}

1 Ответ

2 голосов
/ 15 марта 2020

Вы пытаетесь получить доступ к свойству @Autowired в конструкторе. На этом этапе свойство не может быть подключено автоматически. Чтобы Spring «запек боб», Spring должен создать ваш объект (используя ваш конструктор), и только после этого он применяет механизм автоматической разводки для ввода emailPropertyConfig и cipherCrypt. Поэтому вы не можете получить доступ к двум @Autowired свойствам в конструкторе.

Если вам нужно извлечь некоторые значения из emailPropertyConfig или cipherCrypt, вы можете сделать это в @PostConstruct

@Component
public class Authenticator {

    @Autowired
    PropertyEmailConfiguration emailPropertyConfig;

    @Autowired
    CipherCrypt cipherCrypt;

    private PasswordAuthentication authentication;

    @PostConstruct
    void init() throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException {

      String username = emailPropertyConfig.getEmailConfig().getUsername();
      String password = cipherCrypt.decrypt(emailPropertyConfig.getEmailConfig().getEncryptPassword());
      authentication = new PasswordAuthentication(username, password);
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
      return authentication;
    }
}

или используйте конструктор инъекций:

@Component
public class Authenticator {

    PropertyEmailConfiguration emailPropertyConfig;

    CipherCrypt cipherCrypt;

    private PasswordAuthentication authentication;

    public Authenticator(PropertyEmailConfiguration emailPropertyConfig, CipherCrypt cipherCrypt) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException {

      String username = emailPropertyConfig.getEmailConfig().getUsername();
      String password = cipherCrypt.decrypt(emailPropertyConfig.getEmailConfig().getEncryptPassword());
      authentication = new PasswordAuthentication(username, password);
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
      return authentication;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...