Spring Boot and Working With MBeans [Snippet]
Check out this example code on working with MBeans in your Spring Boot projects.
Join the DZone community and get the full member experience.
Join For FreeThe following example demonstrates how one can manage object operation remotely via the JMX Console. Once you declare your object as MBeans, one can extend the example to apply remote logging without changing log4j, which is very useful in production environments, evicting cache or any other operation that needs to be handled remotely via MBean/JMX.
@ManagedResource
: This Spring annotation applies on the Class Level, and this will declare it as an MBean.
@ManagedOperation
: Apply this on the method level and the method will be shown as an available operation in the JMX console for the MBean.
If there is any input param you want to pass to operation/as in your method, you can use the @ManagedOperationParameters
and @ManagedOperationParameter
annotations.
Below is the sample Class declared as MBean:
@ManagedResource(
objectName="PD:category=MBeans,name=testBean",
description="Managed Bean")
@Component("testMbean")
public class TestMbean {
private String message = "Simple Message";
public TestMbean(){
System.out.println("......TestMbean........");
}
@ManagedOperation
public void resetMessageViaMBean(){
this.message = "Message RESET";
}
public void show(){
System.out.println(message);
}
}
Below is the test Client, written as:
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(ExamplesApplication.class, args);
TestMbean obj = (TestMbean) applicationContext.getBean("testMbean");
obj.show();
try{
//Sleep for 2 min
//Open JConsole and select your process Bean click PD > testBean > Operation > resetMessageViaMBean
//Click on resetMessageViaMBean - if you see testMbean - it is resetting message
//Check whats the message after sleep time is over
Thread.sleep(120000);
}catch(Exception e){
}
obj.show();
}
You can download the code from our Git repository.
Once you run the code, open the JConsole and select your process Bean click PD > testBean > Operation > resetMessageViaMBean. Click on resetMessageViaMBean. If you see testMbean, it is resetting the message. Then, check the message after sleep time is over.
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.2.RELEASE)
......TestMbean........
2019-01-23 15:51:31.394 INFO 7984 --- [ main] c.p.e.examples.ExamplesApplication : Started ExamplesApplication in 0.982 seconds (JVM running for 1.324)
Simple Message
Message RESET
Happy coding!
Opinions expressed by DZone contributors are their own.
Comments