【问题标题】:How to inject CRUDRepository interface to my util class如何将 CRUDRepository 接口注入我的 util 类
【发布时间】:2018-05-27 09:47:30
【问题描述】:

我真的不知道为什么我的 CRUDRepository 接口无法注入。

我在 Spring Boot 上有一个小应用程序并使用 CrudRepository:

public interface ActionLogRepository extends CrudRepository<ActionLog, Integer> {
}

在我的服务类中,我有一个方法:

@Service
public class ActionRecordServiceImpl implements ActionRecordService {

 @Override
    @Transactional
    public void deleteActionRecord(Date date, String domain) {

        Set<Action> actions= myActions...(the code delibrately shortened)

        for (Action a : actions) {
                actionRepository.delete(a);
            }
        }
    }
}

接下来我有我的拦截器 - 我想捕获所有删除操作并将这些日志保存在数据库中:

public class ActionTrackerInterceptor extends EmptyInterceptor {

    // called when record is deleted.
    public void onDelete(Object entity, Serializable id, Object[] state,
            String[] propertyNames, Type[] types) {
        Action act = (Action) entity;
        String action = "DELETED";
        ActionLog actionLog = new ActionLog(...some data inserted...);

        MyActionLogUtil util = new MyActionLogUtil();
        util.logIt("DELETED", actionLog);
        actionLogRepository.save(actionLog);
        System.out.println("Record " + entity + " is deleted.");
    }

而我的方法 util.LogIt 看起来像:

@Component
public class MyActionLogUtilImpl implements ActionyLogUtil {

    private ActionLogRepository actionLogRepository;

    @Autowired
    public void setActionLogRepository(ActionLogRepository actionLogRepository) {
        this.actionLogRepository = actionLogRepository;
    }

    @Override
    public void logIt(String action, ActionLog entity) {

        try {
            ActionLog actionLog = null; // = new ActionLog(...some data inserted...)
            actionLogRepository.save(actionLog);

        } finally {

        }
    }
}

当我的应用程序启动时,MyActionLogUtilImpl 中的方法 setActionLogRepository 被设置并且 ActionLogRepository 被正确注入(不是空值)。但是在调试的时候,在方法 MyActionLogUtilImpl.LogIt IS MY actionLogRepository NULL!

我的 @SpringBootApplication 主类位于包的顶部,因此 ComponentScan 问题不是这里的重点。

问题是为什么?另一笔交易?我真的不知道有什么问题。我已经阅读了互联网上所有类似的主题......请帮助我。谢谢。

问候 马特利

【问题讨论】:

    标签: hibernate spring-boot spring-data-jpa autowired interceptor


    【解决方案1】:

    在你的ActionTrackerInterceptor

    MyActionLogUtil util = new MyActionLogUtil();
    

    您正在手动创建“Util”类的新实例,而不是使用在应用程序启动时创建的 Spring(实际上对您的存储库有正确的引用)。

    这不是关于事务管理,而是关于核心 DI 功能。请务必阅读 Spring docs 以了解 DI 的一般工作原理。

    【讨论】:

    • 啊,非常愚蠢的错误。好的。解决了。而且我已将 INinterceptor 更改为 Hibernate Listener。在这种情况下,为了能够自动装配 bean,我必须应用基于 guylabs.ch/2014/02/22/… 的解决方案,因为 Spring 容器不处理侦听器 - 我们必须稍后手动自动装配 bean。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 2014-05-16
    • 2011-05-06
    • 2015-04-06
    相关资源
    最近更新 更多