如何在Spring中获取@Component的实例?

时间:2015-03-23 16:22:14

标签: java spring spring-boot

我有一个名为RegistrationValidator的@Container类依赖于spring @Repository。通过自动装配在服务或其他容器中获取它的实例很好,但我需要在常规POJO中访问它。如何在不将所有POJO转换为@Container或@Service对象的情况下获取此验证器的实例。有没有办法在RegisterValidator中添加一个返回实例的静态getInstance方法。

package core.dao.validator;

import core.dao.Registration;
import core.repository.RegistrationRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * Validates the Registration DAO.
 *
 * @author Srini Katragadda
 */
@Component
public class RegistrationValidator implements Validator {
    private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationValidator.class);
    private static final int MAX_SIZE = 255;

    private final RegistrationRepository repository;

    @Autowired
    RegistrationValidator(RegistrationRepository repository) {
        this.repository = repository;
    }

    @Override
    public boolean supports(Class clazz) {
        return Registration.class.equals(clazz);
    }

    @Override
    public void validate(Object obj, Errors errors) {
        Registration registration = (Registration) obj;

        // Validate Message Id
        ValidationUtils.rejectIfEmpty(errors, "messageId", "messageId.empty");
        if (registration.getMessageId() != null &&
                registration.getMessageId().length() > MAX_SIZE) 
            errors.rejectValue("messageId", "Size greater than " + MAX_SIZE);

        // Validate for duplicate messageId information
        if (hasDuplicateMessageIdInDatabase(registration)) {
            errors.rejectValue("callouts", "Database has duplicate registration with messageId.");
        }

    }

    /**
     * Check if there is duplicate messageId in database.
     */
    private boolean hasDuplicateMessageIdInDatabase(Registration adsRegistration) {
        return (repository.findByMessageId(adsRegistration.getMessageId()) != null);
    }
}

这是我需要该验证器的实例的地方。检查Builder.build()方法,该方法将验证程序的实例传递给实用程序方法。这工作正常,直到我需要在RegistrationValidator中自动装配@Repository。现在我需要传递存储库的实例以便能够构造验证器,并且想知道如何不将DAO本身作为另一个组件并使用RegistrationValidator自动装配它。

package core.dao;

import core.dao.validator.RegistrationValidator;
import core.util.ValidatorUtil;
import core.util.ToString;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

/**
 * The data access object that holds the information of an Registration.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public final class Registration {

    private String id;
    private String messageId;
    private String version;

    public Registration() {
    }

    private Registration(Builder builder) {
        this.id = builder.id;
        this.messageId = builder.messageId;
        this.version = builder.version;
    }

    public static Builder getBuilder() {
        return new Builder();
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getMessageId() {
        return messageId;
    }

    public void setMessageId(String messageId) {
        this.messageId = messageId;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    /**
     * Builder pattern makes the object easier to construct in one line.
     */
    public static class Builder {

        private String id;

        private String messageId;

        private String version;

        private Builder() {}

        public Builder id(String id) {
            this.id = id;
            return this;
        }

        public Builder messageId(String messageId) {
            this.messageId = messageId;
            return this;
        }


        public Builder version(String version) {
            this.version = version;
            return this;
        }

        public Registration build() {
            Registration entry = new Registration(this);
            return (Registration) ValidatorUtil.validate(entry, new RegistrationValidator());
        }
    }
}

这是完整性的ValidatorUtil.validate代码。

public static Object validate(Object entry, org.springframework.validation.Validator customValidator) {
    Errors errors = new BeanPropertyBindingResult(entry, entry.getClass().getName());
    customValidator.validate(entry, errors);
    if (errors == null || errors.getAllErrors().isEmpty())
        return entry;
    else {
        LOGGER.error(errors.toString());
        throw new InvalidDataException(errors.getAllErrors().toString(), errors);
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用SpringBeanAutowiringSupport通过以下方式将spring bean自动装入pojo:

public class Pojo {

@Autowired
private RegistrationRepository repository

    public void methodWhichRequiresBean() {

        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

        repository.doStuff()

     }

希望这有帮助