Welcome 微信登录

首页 / 软件开发 / JAVA / 使用Spring的JMX annotation让POJO对象输出到JMX

使用Spring的JMX annotation让POJO对象输出到JMX2011-09-09xmatthew自JDK5.0 引入注解(Annotation)后,让Java的开发简化了很多,让开发者几 乎摆脱复杂的

配置文件的烦恼。本文将介绍Spring提供的一套相当于Commons Attribut属 性类的注解和一个策略接口 JmxAttributeSource 的实现类 AnnotationsJmxAttributeSource, 这个类允许 MBeanInfoAssembler 来读这些 注解。本文就给大家展示一下,使用Spring的JMX annotation,如何简单快速让 POJO对象输出到JMX.

里面的出现的类名的功能,在下面介绍,先来看一个例子:

先编写一个POJO对象

1 import java.util.ArrayList;
2 import java.util.List;
3
4 import org.springframework.jmx.export.annotation.ManagedAttribute;
5 import org.springframework.jmx.export.annotation.ManagedOperation;
6 import org.springframework.jmx.export.annotation.ManagedOperationParameter;
7 import org.springframework.jmx.export.annotation.ManagedOperationParameters;
8 import org.springframework.jmx.export.annotation.ManagedResource;
9
10 //实例标记为由JMX管理的资源
11 @ManagedResource(objectName="bean:name=testJmxBean", description="My Managed Bean", log=true,
12 logFile="jmx.log", currencyTimeLimit=15, persistPolicy="OnUpdate", persistPeriod=200,
13 persistLocation="foo", persistName="bar")
14 public class AnnotationTestBean {
15
16 private String name;
17 private int age;
18
19 private List<String> values;
20
21 //把getter或setter标记为JMX的属性
22 @ManagedAttribute(description="The Age Attribute", currencyTimeLimit=1)
23 public int getAge() {
24 return age;
25 }
26
27 public void setAge(int age) {
28 this.age = age;
29 }
30
31 @ManagedAttribute(description="The values Attribute", currencyTimeLimit=1)
32 public List<String> getValues() {
33 values = new ArrayList<String>(2);
34 values.add("hello");
35 values.add("world");
36 return values;
37 }
38
39 @ManagedAttribute(description="The Name Attribute",
40 currencyTimeLimit=20,
41 defaultValue="bar",
42 persistPolicy="OnUpdate")
43 public void setName(String name) {
44 this.name = name;
45 System.out.println("set: " + name);
46 }
47
48 @ManagedAttribute(defaultValue="foo", persistPeriod=300)
49 public String getName() {
50 System.out.println("get: " + name);
51 return name;
52 }
53
54 //把方法标记为JMX的操作
55 @ManagedOperation(description="Add two numbers")
56 @ManagedOperationParameters({
57 @ManagedOperationParameter(name = "x", description = "The first number"),
58 @ManagedOperationParameter(name = "y", description = "The second number")})
59 public int add(int x, int y) {
60 return x + y;
61 }
62
63 public void dontExposeMe() {
64 throw new RuntimeException();
65 }
66 }
67