我想使用 Spring 3 发布 JMX 通知,但希望避免使用NotificationPublisherAware 接口(interface),因为该代码也由不使用 Spring 的应用程序使用。该 bean 使用 MBeanExporter bean 公开。我发现的替代方案需要注册 mbean,我目前使用 Spring 配置来注册 mbean,因此这是一个糟糕的选择。 有没有办法避免使用NotificationPublisherAware接口(interface)但仍然发布通知?
最佳答案
您不必在代码中使用任何 Spring 类。示例:
界面:
import javax.management.MXBean;
@MXBean
public interface SecurityEventsManagerMXBean {
...
@AttributeMetaData(value="UserLoginFailures", defaultValue="0", description="Total user login failures")
public int getUserLoginFailureCount() ;
...
}
bean :
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
public class SecurityEventsManager extends NotificationBroadcasterSupport implements SecurityEventsManagerMXBean {
...
private void notifyUserLoginFailure(...) {
Notification notification = new Notification(...) ;
sendNotification(notification)
userLoginFailureCount++ ;
}
}
这里@AttributeMetaData是一个方便的元注释,定义描述符键:
import javax.management.DescriptorKey;
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AttributeMetaData {
@DescriptorKey("displayName")
String value();
....
}
编辑 3 月 8 日。在 Mbean 之上导出的配置:
<bean id="mbeanServer" class="org.springframework.jmx.support.MBeanServerFactoryBean"
p:locateExistingServerIfPossible="true" />
<bean id="jmxAttributeSource" class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource"/>
<bean id="namingStrategy" class="org.springframework.jmx.export.naming.MetadataNamingStrategy"
p:attributeSource-ref="jmxAttributeSource" />
<bean id="assembler" class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler"
p:attributeSource-ref="jmxAttributeSource" />
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter" lazy-init="false">
<property name="server" ref="mbeanServer"/>
<property name="assembler" ref="assembler"/>
<property name="registrationBehaviorName" value="REGISTRATION_FAIL_ON_EXISTING"/>
<property name="beans">
<map>
<entry>
<key>
<util:constant
static-field="x.y.z.SecurityEventsManager.OBJECT_NAME" />
</key>
<ref bean="securityEventsManager" />
</entry>
</map>
</property>
</bean>
<bean id="securityEventsManager" class="x.y.z.SecurityEventsManager" />
关于java - 在没有NotificationPublisherAware的情况下使用Spring发布JMX通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5179072/