@Configurable-Beans 在 Spring Boot 中不能与 JPA-EntityListeners 一起工作

gof*_*frm 5 spring jpa entitylisteners spring-data-jpa

我在 Spring Boot 应用程序中创建的自定义 jpa-entity 侦听器有一个奇怪的问题。我正在尝试使用 Springs@Configurable机制来配置 EntityListener (如 Springs 中所见AuditingEntityListener),但是一旦在@EntityListenersjpa 实体的-Annotation 中使用了我的 Listener ,Spring 就会拒绝识别它。如果未在 jpa 实体上配置它,则 Spring 会按其应有的方式连接/配置侦听器。

我创建了一个带有 junit-test 的示例项目来演示这个问题:https : //github.com/chrisi/aopconfig/find/master

@SpringBootApplication
@EnableSpringConfigured
@EnableLoadTimeWeaving
public class Application {

  public static void main(String[] args) throws Exception {
    SpringApplication.run(Application.class, args);
  }
}
Run Code Online (Sandbox Code Playgroud)

实体监听器:

/**
 * This bean will NOT be instanciated by Spring but it should be configured by Spring
 * because of the {@link Configurable}-Annotation.
 * <p>
 * The configuration only works if the <code>UnmanagedBean</code> is not used as an <code>EntityListener</code>
 * via the {@link javax.persistence.EntityListeners}-Annotation.
 *
 * @see FooEntity
 */
@Configurable
public class UnmanagedBean {

  @Autowired
  private ManagedBean bean;

  public int getValue() {
    return bean.getValue();
  }
}
Run Code Online (Sandbox Code Playgroud)

我想在 EntityListener/UnmanagedBean 中注入的 Bean:

/**
 * This bean will be instanciated/managed by Spring and will be injected into the
 * {@link UnmanagedBean} in the case the <code>UnmanagedBean</code> is not used as an JPA-EntityListener.
 */
@Component
@Data
public class ManagedBean {
  private int value = 42;
}
Run Code Online (Sandbox Code Playgroud)

应该使用监听器的实体:

/**
 * This simple entity's only purpose is to demonstrate that as soon as
 * it is annotated with <code>@EntityListeners({UnmanagedBean.class})</code>
 * springs configurable mechanism will not longer work on the {@link UnmanagedBean}
 * and therefore the <code>ConfigurableTest.testConfigureUnmanagedBean()</code> fails.
 */
@Entity
@EntityListeners({UnmanagedBean.class}) // uncomment to make the test fail
public class FooEntity {

  @Id
  private Long id;

  private String bar;
}
Run Code Online (Sandbox Code Playgroud)

最后的测试表明,一旦使用监听器,接线就无法正常工作:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class ConfigurableTest {

  /**
   * This test checks if the ManagedBean was injected into the UnmanagedBean
   * by Spring after it was created with <code>new</code>
   */
  @Test
  public void testConfigureUnmanagedBean() {
    UnmanagedBean edo = new UnmanagedBean();
    int val = edo.getValue();
    Assert.assertEquals(42, val);
  }
}
Run Code Online (Sandbox Code Playgroud)

了JUnit测试(在EntityListener / ManagedBean的配线),一旦出现故障作为注释@EntityListeners({UnmanagedBean.class})FooEntity被激活。

这是一个错误还是我错过了其他东西?

为了运行测试,您必须-javaagent:spring-instrument-4.1.6.RELEASE.jar在命令行上使用并在工作目录中提供 jar 文件。

这是我之前问过的一个问题的“精简”版本: @Configurable 在 SpringBoot 应用程序中无法识别