我在Glassfish服务器上配置了这个JNDI自定义资源:
我还部署了一个Web应用程序,在某些时候,我想获得为我的自定义资源的“version”附加属性配置的值。
我的工厂类是这样的:
public class TestCRFactory implements ObjectFactory {
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) {
if (obj instanceof Reference) {
Reference ref = (Reference) obj;
Enumeration<RefAddr> addrs = ref.getAll();
while (addrs.hasMoreElements()) {
RefAddr addr = addrs.nextElement();
if (addr.getType().equals("version")) {
String version = (String) addr.getContent();
System.out.println(version); // it shows me "1"
}
}
}
}
}
如果我查找对象:
Context context = new InitialContext();
Object obj = context.lookup("test/TestCR");
我的代码有效,我可以在工厂类中获得“version”属性,没有任何问题。
但是现在我想获得“version”属性而不查找对象并调用工厂类。我只想通过MBeanServer:
做类似的事情import javax.management.MBeanServer;
import java.lang.management.ManagementFactory;
import javax.management.ObjectName;
...
boolean existsObject = false;
String name = "amx:pp=/domain/resources,type=custom-resource,name=test/TestCR";
ObjectName objName = new ObjectName(name);
try {
MBeanServer mbean = ManagementFactory.getPlatformMBeanServer();
existsObject = mbean.getObjectInstance(objName) != null; // this line works
if (existsObject) {
Object attr = mbean.getAttribute(objName, "version"); // this line doesn't work. it doesn't give me the "version" property I want.
}
} catch (Throwable e) {
existsObject = false;
}
我的问题是:我做错了什么?我应该将属性名称放在name
变量的末尾吗?或类似的东西?
答案 0 :(得分:2)
我明白了!
只需使用getAttribute
这样的方法:
getAttribute("amx:pp=/domain/resources/custom-resource[test/TestCR],type=property,name=version", "Value");
所以我的最终代码是:
boolean existsObject = false;
ObjectName objName = new ObjectName("amx:pp=/domain/resources,type=custom-resource,name=test/TestCR");
try {
MBeanServer mbean = ManagementFactory.getPlatformMBeanServer();
existsObject = mbean.getObjectInstance(objName) != null;
if (existsObject) {
Object attr = mbean.getAttribute("amx:pp=/domain/resources/custom-resource[test/TestCR],type=property,name=version", "Value");
// here 'attr' var is indicating '1', as I've set! (I tested with other values too)
}
} catch (Throwable e) {
existsObject = false;
}