我以编程方式/动态创建原型bean。我想在启动后将这些bean放在jmx控制台中。我怎么能区分它们?我正在使用anotations将我的bean添加到jmx并且我有
@ManagedResource(objectName="bean:name=MybBean")
我需要动态注入objectName。我知道怎么办呢?
这是我的jmx配置:
<context:mbean-export server="mbeanServer" />
<bean id="mbeanServer" class="org.springframework.jmx.support.MBeanServerFactoryBean" />
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter"
lazy-init="false">
<property name="beans">
<map>
<entry key="Server:name=HttpAdaptor">
<bean class="mx4j.tools.adaptor.http.HttpAdaptor">
<property name="port" value="8000" />
<property name="host" value="0.0.0.0" />
<property name="processor">
<bean class="mx4j.tools.adaptor.http.XSLTProcessor" />
</property>
</bean>
</entry>
</map>
</property>
<property name="listeners">
<list>
<!--
-->
<bean class="com.fixgw.jmx.HttpAdaptorMgr">
<property name="mbeanServer" ref="mbeanServer" />
</bean>
</list>
</property>
</bean>
<bean id="sessionMDB" class="com.fixgw.mdb.SessionMDB"
scope="prototype" lazy-init="true">
<constructor-arg ref="0" />
<constructor-arg ref="0" />
</bean>
答案 0 :(得分:15)
您只需执行org.springframework.jmx.export.naming.SelfNaming
:
@Component("MyPrototypeScopedBeanName")
@ManagedResource
public class MyPrototypeScopedBeanName implements SelfNaming
{
@Override
public ObjectName getObjectName() throws MalformedObjectNameException {
return new ObjectName("com.foobar", "name", this.toString());
}
}
答案 1 :(得分:6)
您可以使用JMX命名策略来执行此操作。在工作中我们使用界面:
public interface RuntimeJmxNames {
/** this is the name= part of the object name */
public String getJmxName();
/** this sets the folders as 00=FirstFolder,01=Second */
public String[] getJmxPath();
}
我发布了实施RuntimeMetadataNamingStrategy naming strategy的代码。
然后像下面的Spring bean:
<bean id="jmxAttributeSource"
class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource" />
<bean id="jmxAssembler"
class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler">
<property name="attributeSource" ref="jmxAttributeSource" />
</bean>
<bean id="jmxNamingStrategy" class="com.j256.jmx.RuntimeMetadataNamingStrategy">
<property name="attributeSource" ref="jmxAttributeSource" />
</bean>
<bean id="mbeanExporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="autodetect" value="true" />
<property name="assembler" ref="jmxAssembler" />
<property name="namingStrategy" ref="jmxNamingStrategy" />
<property name="ensureUniqueRuntimeObjectNames" value="false" />
<property name="excludedBeans" ref="excludedJmxBeans" />
</bean>
在您的代码中,您可以执行以下操作:
@ManagedResource(objectName = "foo.com:name=replaced", description = "...")
public class Foo implements RuntimeJmxNames {
...
public String getJmxName() {
// here's where you can make the name be dynamic
return toString();
}
@Override
public String[] getJmxPath() {
return new String[] { "folder" };
}
}
这是关于JMX naming的Spring文档,虽然我不是100%确定它涵盖了自定义命名的东西。
另外,我的SimpleJMX package也会这样做。它使用JmxSelfNaming interface,它允许对象的每个实例定义它自己的bean名称,以使它们独一无二,并且与Spring一起使用。