我在 Spring Boot 应用程序中创建的自定义 jpa 实体侦听器遇到了一个奇怪的问题。我正在尝试使用弹簧@Configurable
配置 EntityListener 的机制(如 Springs 中所示)AuditingEntityListener
)但是 Spring 拒绝在我的监听器被用于@EntityListeners
-jpa 实体上的注释。如果未在 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);
}
}
实体监听器:
/**
* 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();
}
}
我想要注入到实体监听器/非托管 Bean 中的 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;
}
应使用侦听器的实体:
/**
* 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;
}
最后的测试表明,一旦使用监听器,接线就无法工作:
@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);
}
}
junit-test(EntityListener/ManagedBean 的连接)一旦失败
注释@EntityListeners({UnmanagedBean.class})
in FooEntity
被激活。
这是一个错误还是我错过了其他东西?
为了运行测试,您必须使用-javaagent:spring-instrument-4.1.6.RELEASE.jar
在命令行上提供工作目录中的 jar 文件。
这是我之前提出的问题的“浓缩”版本:@Configurable 在 Spring Boot 应用程序中无法识别