Announcement Announcement Module
Collapse
No announcement yet.
Access Spring bean from ServletContextListener Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Access Spring bean from ServletContextListener

    I looked around the forum before posting this, so please forgive me if this is a very fundamental question!

    I am trying to access a Spring bean (id="beanDAO") from an implementation of ServletContextListener, so I can cache some data in application scope.
    Code:
    public class appListener implements ServletContextListener {
    	public void contextInitialized(ServletContextEvent sce) {
    		ServletContext ctx = sce.getServletContext();
    		WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(ctx);
    		IBeanDAO beanRep = (IBeanDAO) springContext.getBean("beanDAO");
    		ctx.setAttribute("INFO", beanRep.getInfoFromDB());
    	}
    But the server (JBoss) throws an NullPointerException during startup on the last line, which is implying that beanRep is NULL.

    ERROR [[/WebApp]] Exception sending context initialized event to listener instance of class com.xyz.web.listeners.appListener
    java.lang.NullPointerException
    at com.xyz.web.listeners.appListener.contextInitializ ed(appListener.java:82)

    What am I missing? Are there better practices to accessing Spring beans and using the application scope as a cache for frequently used data?

    Thanks.

    Ashwin

  • #2
    You can only do this if your Listener is executed AFTER the ContextLoaderListener, else there will be no available ApplicationContext. You can also only access beans defined in the root application context not those from the DispatcherServlet!!!

    Comment


    • #3
      Thank you so much for pointing this out Marten. It feels obvious, now that you pointed me to the exact problem!

      All I had to do was make a simple change in web.xml to reorder the listeners, and it worked perfectly.

      before... (causing the NullPointerException since there is no ApplicationContext yet)
      Code:
      <listener>
          <listener-class>com.xyz.web.listeners.appListener</listener-class>
      </listener>
      <listener>
          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      after... (works now)
      Code:
      <listener>
          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      <listener>
          <listener-class>com.xyz.web.listeners.appListener</listener-class>
      </listener>

      Comment


      • #4
        Thanks for the post. it helped me.

        Comment


        • #5
          hello i have the same problem and i try this solution but it not work for me please help me its very important
          ApplicationListener.xml:
          Code:
          <?xml version="1.0" ?>
          <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"
          	xmlns:tx="http://www.springframework.org/schema/tx" 
          	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
          	<context:component-scan base-package="com/adweb/" />
          
          	<bean
          		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
          		<property name="location">
          			<value>/WEB-INF/database.properties</value>
          		</property>
          	</bean>
          
          	<bean id="dataSource"
          		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
          		<property name="driverClassName" value="${jdbc.driverClassName}" />
          		<property name="url" value="${jdbc.url}" />
          		<property name="username" value="${jdbc.username}" />
          		<property name="password" value="${jdbc.password}" />
          	</bean>
          	<bean id="sessionFactory"
          		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" scope="singleton">
          
          		<property name="dataSource">
          			<ref bean="dataSource" />
          		</property>
          
          		<property name="hibernateProperties">
          			<props>
          				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
          				<prop key="hibernate.show_sql">true</prop>
          			</props>
          		</property>
          
          		<property name="mappingResources">
          			<list>		
          				<value>com/adweb/bean/UserAuth.hbm.xml</value>
          				<value>com/adweb/bean/Dfaupdate.hbm.xml</value>
          				<value>com/adweb/bean/Advertiser.hbm.xml</value>
          				<value>com/adweb/bean/Campaign.hbm.xml</value>
          				<value>com/adweb/bean/Site.hbm.xml</value>
          				<value>com/adweb/bean/Placement.hbm.xml</value>
          			</list>
          		</property>
          
          	</bean>
          
          </beans>
          Web.xml
          Code:
          <?xml version="1.0" encoding="UTF-8"?>
          <web-app id="WebApp_ID" version="2.4" 
          	xmlns="http://java.sun.com/xml/ns/j2ee" 
          	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
          	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
          	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
           
          	<display-name>AdWebMaroc</display-name>
           
          	<!-- Spring beans -->
          	<context-param>
          		<param-name>contextConfigLocation</param-name>
          		<param-value>/WEB-INF/applicationContext.xml </param-value>
          	</context-param>
           
          	<context-param>
          		<param-name>log4jConfigLocation</param-name>
          		<param-value>/WEB-INF/log4j.properties</param-value>
          	</context-param>
          	<listener>
          		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
          	</listener>
          	<listener>
          		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
          	</listener>
          	<listener>
          		<listener-class>com.adweb.bo.util.ApplicationListener</listener-class>
          	</listener>
           
           
          	
              
          	
          	
          	<filter>
          		<filter-name>struts2</filter-name>
          		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
          	</filter>
          	<filter-mapping>
          		<filter-name>struts2</filter-name>
          		<url-pattern>/*</url-pattern>
          	</filter-mapping>
          	  <welcome-file-list>
              <welcome-file>/content/welcome/index.jsp</welcome-file>
            </welcome-file-list>
           
          </web-app>
          table advertisers:
          Code:
          CREATE TABLE `advertisers` (
            `advertiserid` int(11) NOT NULL,
            `advertisername` varchar(200) DEFAULT NULL,
            PRIMARY KEY (`advertiserid`)
          )
          class Advertiser:
          Code:
          public class Advertiser {
          	private int advertiserid;
          	private String advertisername;
          	
          	public Advertiser(int advertiserid, String advertisername) {
          		super();
          		this.advertiserid = advertiserid;
          		this.advertisername = advertisername;
          	}
          	public int getAdvertiserid() {
          		return advertiserid;
          	}
          	public void setAdvertiserid(int advertiserid) {
          		this.advertiserid = advertiserid;
          	}
          	public String getAdvertisername() {
          		return advertisername;
          	}
          	public void setAdvertisername(String advertisername) {
          		this.advertisername = advertisername;
          	}
          }
          Fichier mapping:
          Code:
          <?xml version="1.0"?>
          <!DOCTYPE hibernate-mapping PUBLIC
          	"-//Hibernate/Hibernate Mapping DTD//EN"
          	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
          
          <hibernate-mapping>
          	<class name="com.adweb.bean.Advertiser" table="advertisers">
          		<id
          			column="advertiserid"
          			name="advertiserid"
          			type="integer"
          		>
          		<generator class="assigned"/> 
          		</id>
          		
          		<property
          			column="advertisername"
          			length="200"
          			name="advertisername"
          			not-null="false"
          			type="string"
          		 />
          	</class>
          </hibernate-mapping>
          Job:
          Code:
          package com.adweb.bo.job;
          
          import org.springframework.beans.factory.annotation.Autowired;
          import org.springframework.context.ApplicationContext;
          import org.springframework.context.support.ClassPathXmlApplicationContext;
          
          import com.adweb.bean.Advertiser;
          import com.adweb.bo.dfa.DfaUpdate;
          import com.doubleclick.dart.DartException;
          
          public class GoogleDBUpdate implements org.quartz.Job {
          
          	public static void main(java.lang.String args[]) throws DartException {
          		GoogleDBUpdate.executeJob();
          	}
          
          	public void execute(org.quartz.JobExecutionContext arg0)
          			throws org.quartz.JobExecutionException {
          		try {
          			GoogleDBUpdate.executeJob();
          		} catch (DartException e) {
          			// TODO Auto-generated catch block
          			e.printStackTrace();
          		}
          	}
          
          	private static void executeJob() throws DartException {
          		System.out.println("bonjour");
          		DfaUpdate dfa = new DfaUpdate();
          		dfa.remplierDataBase();
          
          	}
          }
          DfaUpdate:
          Code:
          public void remplierDataBase() throws DartException {
          		Advertiser advertiserdfa = null;
          		com.adweb.bean.Advertiser advertiser;
          		Date todayDate = new Date();
          
          		for (Enumeration advenum = advmDfaOrganization.getAdvertisers(); advenum
          				.hasMoreElements();) {
          			advertiserdfa = (Advertiser) advenum.nextElement();
          			advertiser = new com.adweb.bean.Advertiser(advertiserdfa.getId(),
          					advertiserdfa.getName());
          			
          				advertiserBo.update(advertiser);
          			
          		}
          
          	}
          }
          AdvertiserDao:
          Code:
          package com.adweb.dao;
          
          import java.util.List;
          import org.hibernate.SessionFactory;
          import org.springframework.beans.factory.annotation.Autowired;
          import org.springframework.beans.factory.annotation.Qualifier;
          import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
          import org.springframework.stereotype.Repository;
          import com.adweb.bean.Advertiser;
          
          @Repository("advertiserDao")
          public class AdvertiserDaoImpl extends HibernateDaoSupport implements
          		Dao<Advertiser> {
          	@Autowired
          	public AdvertiserDaoImpl(
          			@Qualifier("sessionFactory") SessionFactory sessionFactory) {
          		super.setSessionFactory(sessionFactory);
          
          	}
          
          	@Override
          	public void add(Advertiser object) {
          		getHibernateTemplate().save(object);
          
          	}
          
          	@Override
          	public void update(Advertiser object) {
          		getHibernateTemplate().update(object);
          
          	}
          
          	@Override
          	public void delete(Advertiser object) {
          		getHibernateTemplate().delete(object);
          
          	}
          
          	@Override
          	public List<Advertiser> findAll() {
          		return (List<Advertiser>) getHibernateTemplate()
          				.find("from Advertiser");
          	}
          
          	public List<Advertiser> findById(int id) {
          		return (List<Advertiser>) getHibernateTemplate().find(
          				"from Advertiser where advertiserid = ? " , id);
          	}
          }
          AdvertiserBo:

          Code:
          package com.adweb.bo;
          
          import java.util.List;
          import org.springframework.beans.factory.annotation.Autowired;
          import org.springframework.stereotype.Service;
          
          import com.adweb.bean.Advertiser;
          import com.adweb.dao.AdvertiserDaoImpl;
          
          @Service("advertiserBo")
          public class AdvertiserBoImpl implements Bo<Advertiser> {
          
          	@Autowired
          	private AdvertiserDaoImpl advertiserDao;
          
          	public AdvertiserDaoImpl getAdvertiserDao() {
          		return advertiserDao;
          	}
          
          	public void setAdvertiserDao(AdvertiserDaoImpl advertiserDao) {
          		this.advertiserDao = advertiserDao;
          	}
          
          	@Override
          	public void add(Advertiser objet) {
          		advertiserDao.add(objet);
          
          	}
          
          	@Override
          	public void update(Advertiser objet) {
          		
          		if (this.findById(objet.getAdvertiserid()) != null)
          			advertiserDao.update(objet);
          		else
          			add(objet);
          
          	}
          
          	@Override
          	public void delete(Advertiser objet) {
          		advertiserDao.add(objet);
          
          	}
          
          	public List<Advertiser> findAll() {
          		return advertiserDao.findAll();
          
          	}
          
          	public Advertiser findById(int id) {
          		List<Advertiser> advertiserList = advertiserDao.findById(id);
          		if (advertiserList != null && advertiserList.size() > 0) {
          			return advertiserList.get(0);
          
          		}
          		return null;
          
          	}
          
          }

          Comment

          Working...
          X