使用LocalSessionFactoryBean设置JMX支持

时间:2015-03-10 17:01:03

标签: java hibernate jmx jconsole

有一个带有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;
    }

JConsole

1 个答案:

答案 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上调用getObjectsessionFactoryBean来获取SessionFactory实例。请注意,您必须检查getObject是否在将来的调用中返回相同的对象。您不希望它返回一个实例以用于您的MBean,另一个实例用于您应用的其余部分。