我在Spring启动应用程序中创建的自定义jpa实体监听器出现了一个奇怪的问题。我尝试使用Springs @Configurable
机制来配置EntityListener(如弹簧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);
}
}
EntityListener:
/**
* 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();
}
}
我希望在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;
}
应使用监听器的实体:
/**
* 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;
}
最后,测试表明,只要使用Listener,接线就不能正常工作:
@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的连线)一旦失败就会失败
<{1}}中的注释@EntityListeners({UnmanagedBean.class})
已激活。
这是一个错误还是我错过了其他什么?
要运行测试,您必须在命令行上使用FooEntity
,并在工作目录中提供jar文件。
这是&#34;浓缩&#34;我之前问过的一个问题的版本: @Configurable not recognized in SpringBoot Application