Saturday 19 November 2011

EJB use third party libraries

Assume the EJB project (containing the session bean, entity bean) is named ‘ejb3-jpa’, the EAR project is named ‘ejb3-ear’

An EJB session bean needs to use a third party library (e.g. Log4j)

import org.apache.log4j.Logger;

@Stateless(name="stateless")
@Local(Session.class)
public class StatelessSessionBean implements Session {

    private int result;
    private Logger logger = Logger.getLogger(StatelessSessionBean.class);
    
    @Override
    public void add() {
        logger.info("add");
        result++;
    }

    @Override
    public int get() {
        return result;
    }
}

Without any more changes, we will get a NoClassDefFoundError:

Caused by: java.lang.NoClassDefFoundError: org/apache/log4j/Logger
at session.StatelessSessionBean.<init>(StatelessSessionBean.java:13)

This is because the dependent jar file (Log4j.jar) won’t be automatically deployed to the server. So we need to manually add the dependent jar file to the EAR project.

Right click on ‘ejb3-ear’, and click on ‘Properties’



Click on ‘Add External JARs’



Add the ‘Log4j.jar’ file into the Java EE modules list

In ‘ejb3-jpa’ project, open the MANIFEST.MF file under META-INF



Enter the Log4j jar name following the Class-Path:

Manifest-Version: 1.0
Class-Path: log4j-1.2.14.jar

Now the StatelessSessionBean class is able to find the Log4j classes it is dependent on.

Appendix

Class loading rule