SpringBoot中的@EntityListeners

Nuñ*_*ada 5 java spring spring-boot

我创建了这个 EntityListener:

@Slf4j
@Component
public class AListener {

    private final ARepository aRepository;

    public AListener(ARepository aRepository) {
        this.aRepository = aRepository;
    }


    ...
}
Run Code Online (Sandbox Code Playgroud)

我在这里使用的:

@Entity
@EntityListeners(AListener.class)
@Table(name = "CAT")
@NoArgsConstructor
@AllArgsConstructor
public class Cat implements Serializable {
..
}
Run Code Online (Sandbox Code Playgroud)

但我看到这个错误:Class 'AListener' should have [public] no-arg constructor

并在日志中:

Exception Description: Error encountered when instantiating the class [class com.poli.listener.AListener].
Internal Exception: java.lang.InstantiationException: com.poli.listener.AListener]
Run Code Online (Sandbox Code Playgroud)

Sem*_*kov 4

EntityListener是 JPA 功能,而不是 Spring 功能。您不需要将侦听器声明为 a @Component,因为 JPA 提供程序将实例化它。

这就是这里实际发生的情况:

  1. Spring实例化一个AListenerbean并注入ARepository依赖项。
  2. JPA 提供程序发现这AListener是一个实体侦听器并尝试实例化它。为此,需要无参数构造函数(请记住,JPA 提供者对 Spring 及其 beans 一无所知)
  3. 实例化失败,因为找不到无参数构造函数

您可以通过删除ARepository依赖项并在构造函数内添加一些日志记录语句来检查它。

如果您确实需要侦听器中的一些 Spring bean,您可以将它们作为某些实用程序类中的静态字段进行访问。