有一个带有Hibernate JMX Statistics Service和LocalSessionFactoryBean
配置的java配置bean。我没有看到通过已经实例化的LocalSessionFactoryBean
获得SessionFactory的任何可能性。目标是启用JMX支持,以便JConsole能够访问Hibernates统计信息。如果我创建新的SessionFactory它将是重复的。如何进行此配置?
@Bean
public LocalSessionFactoryBean sessionFactory(){
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
// JMX statistics
SessionFactory sf = ...; // ???
StatisticsService statsMBean = new StatisticsService();
statsMBean.setSessionFactory(sessionFactoryBean.);
statsMBean.setStatisticsEnabled(true);
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
mBeanServer.registerMBean(statsMBean, new ObjectName("Hibernate:application=Statistics"));
return sessionFactoryBean;
}
答案 0 :(得分:1)
编写新的@Bean
方法以公开StatisticsService
@Autowired
@Bean
public StatisticsService service(SessionFactory sessionFactory) {
StatisticsService statsMBean = new StatisticsService();
statsMBean.setSessionFactory(sessionFactory);
statsMBean.setStatisticsEnabled(true);
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
mBeanServer.registerMBean(statsMBean, new ObjectName("Hibernate:application=Statistics"));
return statsMBean;
}
或者,您可以在afterPropertiesSet
上调用getObject
和sessionFactoryBean
来获取SessionFactory
实例。请注意,您必须检查getObject
是否在将来的调用中返回相同的对象。您不希望它返回一个实例以用于您的MBean,另一个实例用于您应用的其余部分。