Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Wednesday, June 4, 2014

Sending emails with attachments

In this example, I will show you how to use Java and Spring to send an email with attachments. Here is the main class to start things off:
package com.noushin.spring.email;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;

import javax.mail.MessagingException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Main class to demonstrate sending an email with attachments.
 * 
 * @author nbashir
 * 
 */
public class EmailMain {

   public static void main(String[] args) {
      ApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml");
      try {
         if (ctx != null) {
            Emailer emailer = ctx.getBean(Emailer.class);
            Collection<File> attachments = new ArrayList<File>();
            File attachment = new File("/home/nbashir/file.txt");
            attachments.add(attachment);
            emailer.sendEmail("Test Email", "Please see attached file(s).", attachments);
         }
      }
      catch (MessagingException me) {
         // TODO Auto-generated catch block
         me.printStackTrace();
      }
      catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}
And Emailer class that generates an Email message, attaches files to it, and delivers.
package com.noushin.spring.email;

import java.io.File;
import java.util.Collection;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Component
public class Emailer {

   @Autowired
   @Qualifier("mailSender")
   private JavaMailSender mailSender;

   @Value("${email.recipients}")
   private String emailRecipients;
   @Value("${email.from}")
   private String emailFrom;
   @Value("${email.reply.to}")
   private String emailReplyTo;

   /**
    * Send an email with attachments
    * 
    * @param subject email's subject line
    * @param body email's body
    * @param attachments list of attachments
    * 
    * @throws MessagingException 
    */
   public void sendEmail(String subject, String body, Collection<File> attachments) throws MessagingException {

      MimeMessage message = mailSender.createMimeMessage();
      MimeMessageHelper msgHelper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED);

      String[] recipients = getRecipients(emailRecipients);
      if (recipients != null) {
         for (int i = 0; i < recipients.length; i++)
            msgHelper.addTo(recipients[i]);
      }
      msgHelper.setFrom(emailFrom);
      msgHelper.setReplyTo(emailReplyTo);
      msgHelper.setSubject(subject);
      msgHelper.setText(body, true);

      if (attachments != null) {
         String filename = null;
         for (File attachment : attachments) {
            filename = attachment.getName();
            FileSystemResource res = new FileSystemResource(attachment);
            msgHelper.addAttachment(filename, res);
         }
      }

      mailSender.send(message);
   }

   /**
    * Return a list of strings
    * 
    * @param csvList a string containing a comma separated values 
    * @return a list of strings
    */
   public String[] getRecipients(String csvList) {
      String[] values = null;
      if (csvList != null) {
         values = csvList.split(",");
         for (int i = 0; i < values.length; i++)
            values[i] = values[i].trim();
      }
      return values;
   }
}
The pom file you need:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.noushin.spring</groupId>
    <artifactId>email</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>email</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.0.3.RELEASE</spring.version>
        <java.mail>1.4.7</java.mail>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>${java.mail}</version>
        </dependency>

    </dependencies>

</project>

And application context:
<?xml version="1.0" encoding="UTF-8"?>
<beans 
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="file:/home/nbashir/email.properties" />
    
    <!-- Activate annotation configured components -->
    <context:annotation-config />

    <!-- Scan components for annotations within the configured package -->
    <context:component-scan base-package="com.noushin.spring.email" />
        
    <!-- Email handler -->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${email.host}" />
        <property name="port" value="${email.port}" />
    </bean>

</beans>

Monday, February 24, 2014

Spring & MongoTemplate

To keep up with Spring templates theme, I will show you how to use MongoTemplate to access MongoDB. Assuming you are already familiar with MongoDB and the fact that it's a document centric datastore, the first thing we should do is define objects representing documents. In this tutorial, my application will manage books in a MongoDB database. Here is the definition of a book stored as a document.
package com.noushin.spring.monspr.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

/**
 * This class represents a book as a MongoDB document.
 * 
 * @author nbashir
 * 
 */
@Document
public class Book {

   @Id
   private String id;

   @Indexed
   private String name;

   private String author;

   public Book(String id, String name, String author) {
      super();
      this.id = id;
      this.name = name;
      this.author = author;
   }

   public String getId() {
      return id;
   }

   public void setId(String id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getAuthor() {
      return author;
   }

   public void setAuthor(String author) {
      this.author = author;
   }
}
Now I need a class to access books in MongoDB. This is where I will utilize MongoTemplate.
package com.noushin.spring.monspr.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;

import com.noushin.spring.monspr.model.Book;

/**
 * This class handles accessing books in MongoDB.
 * 
 * @author nbashir
 *
 */
@Repository
public class BookRepositroy {
   
   @Autowired
   MongoTemplate mongoTemplate;
      
   public void save(Book book) {
      mongoTemplate.save(book);
   }
   
   public void save(List<Book> books) {
      mongoTemplate.save(books);
   }

   public Book get(String id) {
      return mongoTemplate.findById(id, Book.class);
   }
   
   public List<Book> getAll() {
      return mongoTemplate.findAll(Book.class);
   }
   
   public void delete(Book book) {
      mongoTemplate.remove(book);
   }
}
And a typical class to place in the service layer:
package com.noushin.spring.monspr.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.noushin.spring.monspr.dao.BookRepositroy;
import com.noushin.spring.monspr.model.Book;

/**
 * This class handles any business logic related to handling books.
 * 
 * @author nbashir
 *
 */
@Component
public class BookService {

   @Autowired 
   BookRepositroy bookRepo;
   
   public void save(Book book) {
      bookRepo.save(book);
   }
   
   public void save(List<Book> books) {
      bookRepo.save(books);
   }

   public Book get(String id) {
      return bookRepo.get(id);
   }
   
   public List<Book> getAll() {
      return bookRepo.getAll();
   }
   
   public void delete(Book book) {
      bookRepo.delete(book);
   }
}
And last, but not least, a class to load Spring context and do some basic data access operations in regards to our books example:
package com.noushin.spring.monspr;

import java.util.ArrayList;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.noushin.spring.monspr.model.Book;
import com.noushin.spring.monspr.service.BookService;

/**
 * Main class to demonstrate accessing MongoDB with Spring Data and MongoTemplate.
 * 
 * @author nbashir
 *
 */
public class MongoDbMain {

   final static Logger logger = Logger.getLogger(MongoDbMain.class);

   public static void main(String[] args) {
      try {
         ApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml");
         if (ctx != null) {
            logger.info(ctx.getApplicationName() + "MongoDbMain successfuly started. ");
            BookService service = ctx.getBean(BookService.class);
                       
            Book book;
            book = new Book(UUID.randomUUID().toString(), "Ragtime", "E.L. Doctrow");
            service.save(book);
            book = new Book(UUID.randomUUID().toString(), "The March", "E.L. Doctrow");
            service.save(book);
            book = new Book(UUID.randomUUID().toString(), "Andrew's Brain", "E.L. Doctrow");
            service.save(book);
            book = new Book(UUID.randomUUID().toString(), "Wild: From Lost to Found on the Pacific Crest Trail ",
                  "Cheryl Strayed");
            service.save(book);

            ArrayList<Book> books = (ArrayList<Book>) service.getAll();
            for (int i = 0; i < books.size(); i++)
               System.out.println("Book " + i + " : " + books.get(i).getId() + " - " + books.get(i).getName());
            
            for (int i = 0; i < books.size(); i++)
               service.delete(books.get(i));
      
            ArrayList<Book> deltedBooks =  (ArrayList<Book>) service.getAll();
            if (deltedBooks.size() > 0 ) {
               for (int i = 0; i < deltedBooks.size(); i++)
                  System.out.println("Book " + i + " : " + deltedBooks.get(i).getId() + " - " + deltedBooks.get(i).getName());
            }
            else
               System.out.println("All book are successfully removed.");

         }
      }
      catch (Exception ex) {
         logger.error("MongoDbMain encountered an error and ended.", ex);
      }
   }
}
Now that we have the basic Java code in place, we need to configure our app, so it knows how to access the datastore. As with any other Spring application, configuration details are in application-context.xml.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- Activate annotation configured components -->
    <context:annotation-config />

    <!-- Scan components for annotations within the configured package -->
    <context:component-scan base-package="com.noushin.spring.monspr" />

    <!-- Mongo config -->
    <!-- Factory bean that creates the Mongo instance -->

    <bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
        <property name="host" value="[your-mongodb-host]" />
    </bean>

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongo" ref="mongo" />
        <constructor-arg name="databaseName" value="nbdb" />
    </bean>
</beans>
In the above configuration, my app will be connecting to "nbdb" database, with MongoDB running on a server specified by "host" property of MongoFactoryBean.

To complete this example, here is my pom.xml where application dependecies are listed:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.noushin.spring</groupId>
  <artifactId>monspr</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>monspr</name>
  <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <junit.version>4.11</junit.version>
        <log4j.version>1.2.17</log4j.version>
        <spring.version>3.2.4.RELEASE</spring.version>
        <spring.data.version>1.3.4.RELEASE</spring.data.version>
    </properties>

    <dependencies>
        <!-- Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        
        <!-- Logging -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
            
        <!-- Spring Data -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>${spring.data.version}</version>
        </dependency>
        
        <!-- Spring Context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>
</project>

Saturday, January 12, 2013

Spring & Testing

I think unit testing Spring components is really cool. You can have a separate application context just for testing purposes, which will not conflict with your application's runtime context when developing.

Here is a couple of steps you need to take to test your components using Spring testing.

1. Add the following dependency to your pom file:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>org.springframework.test</artifactId>
    <version>${spring.version}</version>
    <scope>test</scope>
</dependency>
where
    <spring.version>3.2.0.RELEASE</spring.version>

2. In your test/resources folder, your need to a create a package matching the your Test class, and create a context file with a name that matches your Test class name.

Here is an example:

Lets say you are testing a class called MessageProducer.
package com.noushin.spring.jms.producer;

import java.io.IOException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

@Component
public class MessageProducer {

   final static Logger logger = Logger.getLogger(MessageProducer.class);

   @Autowired
   private JmsTemplate jmsTemplate;

   public void produce() throws Exception {
      
      if (jmsTemplate != null) {
         MessageCreator mc = new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
               try {
                  String jmsMessage = FileUtils.readFileToString(FileUtils.toFile(this.getClass().getResource("/jms-message.txt")));
                  TextMessage message = session.createTextMessage(jmsMessage);
                  logger.info(">>>>>Sending message: " + jmsMessage);
                  return message;
               } 
               catch (IOException ioe) {
                  logger.error("File not found : ", ioe);
                  return null;
               }
               catch (JMSException je) {
                  logger.error("JMS Exception : ", je);
                  return null;
               }
            }
         };
         jmsTemplate.send(mc);
      }
   }
}

3. Here is your JUnit test case, ~workspace/jms/src/test/java/com/noushin/spring/jms/producer/MessageProducerTest.java
package com.noushin.spring.jms.producer;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MessageProducerTest {
   
   @Autowired
   protected MessageProducer producer;
   
   @Test
   public void testProduce() {
      try {
         producer.produce();
         assert(true);
      } 
      catch (Exception e) {
         e.printStackTrace();
      }
   }
}

4. Corresponding test context is at ~workspace/jms/src/test/resources/com/noushin/spring/jms/producer/MessageProducerTest-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:amq="http://activemq.apache.org/schema/core" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.noushin.spring.jms" />
    <context:annotation-config />

    <!-- ActiveMQ destinations to use -->
    <amq:queue id="destination" physicalName="TestQ" />
    
    <!-- ActiveMQ broker URL -->
    <amq:connectionFactory id="jmsFactory" brokerURL="tcp://localhost:61616" />

    <!-- Spring JMS ConnectionFactory -->
    <bean id="singleConnectionFactory" 
          class="org.springframework.jms.connection.SingleConnectionFactory"
          p:targetConnectionFactory-ref="jmsFactory"/>
    
    <!-- Spring JMS Producer Configuration -->
    <bean id="jmsProducerTemplate" class="org.springframework.jms.core.JmsTemplate"
        p:connectionFactory-ref="singleConnectionFactory"
        p:defaultDestination-ref="destination"/>
        
</beans>

Alternatively, if there is a context configuration that can be reused by test classes in different packages, you can specify its location on classpath:
@ContextConfiguration(locations={"classpath:/com/noushin/spring/jms/producer/MessageProducerTest-context.xml"})

5. If in Eclipse, right click your test class and run it as JUnit Test. :)

Tuesday, December 25, 2012

Spring 3 & Properties

This blog will show you how to load properties using Spring with annotations.

1. Write a class to load and give access to properties:

package com.springtutorial.props;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class AppConfig {

    @Value("${text.to.print}")
    private String text;

    public String getText() {
        return text;
    }
}


2. Here is your class that needs access to properties:

package com.springtutorial.props;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class App {

   @Autowired
   AppConfig appConfig;

   public static void main(String[] args) {
     ApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml");
     AppConfig app = (AppConfig)ctx.getBean("appConfig");
     System.out.println("Text : " + app.getText());
   }
}


3. Here is what you need in ~/workspace/springtutorial/src/main/resources/application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.springtutorial.props" />
    <context:annotation-config />
    <context:property-placeholder location="classpath:app.properties" />

</beans>


4. Your property file is ~/workspace/springtutorial/src/main/resources/app.properties
text.to.print=Hello World!


5. Finally, this is how you need set up your pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.springtutorial</groupId>
  <artifactId>props</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>props</name>
  <url>http://maven.apache.org</url>

  <properties>
        <junit.version>4.10</junit.version>
        <spring.version>3.0.6.RELEASE</spring.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
  </dependencies>
</project>


5. Time to run App.java as a Java Application to see the results.

Tuesday, February 22, 2011

Spring 3 & JMX

In this blog I will show you how to expose your POJOs as Managed Beans using Spring. I am assuming you are somewhat familiar with JMX, Spring, Maven, Tomcat and Java.

To expose your object as a managed bean in Tomcat, you need to register it with a MBeanServer. Spring easily allows you to do so using its config file.

Exposing your POJO as a managed bean

Here is an example of a POJO:

package com.mycompany.myapp.test;

public class TestManagedBean {

private String id;
private String name;

public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Before modifying your Spring context configuration file, edit your pom.xml to include Spring jar files required for JMX.

Here is my sample pom.xml:

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>3.0.0.RELEASE</spring.version>
</properties>

<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>


Modify your Spring context configuration file as follows. My file is called application-context.xml and is in ~myapp/src/main/resources/


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<context:component-scan base-package="com.mycompany.myapp"/>

<!-- this bean must not be lazily initialized if the exporting is to happen -->
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter" lazy-init="false">
<property name="beans">
<map>
<entry key="bean:name=testBean1" value-ref="testBean"/>
</map>
</property>
<property name="registrationBehaviorName" value="REGISTRATION_REPLACE_EXISTING"/>
</bean>

<bean id="testBean" class="com.mycompany.myapp.test.TestManagedBean">
<property name="id" value="1"/>
<property name="name" value="Abc Def"/>
</bean>

</beans>


Accessing a managed bean

 
package com.mycompany.myapp.testjmx;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mycompany.myapp.test.TestManagedBean;

public class JmxTestClient {

public static void getMBeanServer() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
TestManagedBean service = context.getBean(TestManagedBean.class);

String name = service.getName();
System.out.println("Name = " + name);

}
}


You can now call JmxTestClient.getMBeanServer() to get access to the managed bean.

You can also use "jconsole" to view registered managed beans with Tomcat's MBeanServer. To do so, start Tomcat with "-Dcom.sun.management.jmxremote" option.
Run "jconsole" from command line. When it comes up, select and connect to "org.apache.catalina.startup.Bootstrap start" listed as a "Local Process". Click on the "MBeans" tab. You can find "jmxtest" listed under "Catalina/Manager".