Problem with Spring integration

Hi!

I’m trying to get a simple vaadin project working with spring as explained in
spring wiki
.

My 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:jee="http://www.springframework.org/schema/jee"
  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.0.xsd
    http://www.springframework.org/schema/jee 
    http://www.springframework.org/schema/jee/spring-jee-2.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

  <!-- Data classes -->
  <bean id="userDao"
    class="com.collapsux.filer.datalevel.impl.UserDaoImpl">
  </bean>

  <bean id="logDao"
    class="com.collapsux.filer.datalevel.impl.FilerLogDaoImpl">
  </bean>
  

  <!-- Service components -->
  <bean id="filerService"
    class="com.collapsux.filer.services.impl.FilerServiceImpl">
    <property name="userDao">
      <ref bean="userDao" />
    </property>
    <property name="logDao">
      <ref bean="logDao" />
    </property>
  </bean>

  <!-- Database connection -->
  <bean id="datasource"
    class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName"
      value="org.hsqldb.jdbcDriver" />
    <property name="url" value="jdbc:hsqldb:mem:filer" />
    <property name="username" value="sa" />
    <property name="password" value="" />
  </bean>

  <!-- JPA-definitions -->

  <!-- Factory for entitymanagers -->
  <bean id="emf"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="datasource" />
    <property name="jpaVendorAdapter">
      <bean
        class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    </property>
  </bean>

  <!-- Notice @PersistenceContext-annotations -->
  <context:annotation-config />

  <!-- Transaction management -->
  <bean id="transactionManager"
    class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory"
      ref="emf" />
  </bean>

  <!-- Notice @Transactional annotations -->
  <tx:annotation-driven />
  
  <!-- Turn on AspectJ @Configurable support --> 
<context:spring-configured />

<context:component-scan base-package="com.collapsux.filer" />

<!--  Turn on @Autowired, @PostConstruct etc support  -->
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" /> 

</beans>

and my web.xml contains this:


<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:context.xml</param-value>
  </context-param>

My main class starts:


@Configurable(preConstruction = true)
public class FilerApplication extends Application
{
	
	private static final long serialVersionUID = 6777561160414111445L;

	public static final String VERSION = "1.0";
	
	@Autowired
	private FilerService service;
	private User currentUser;
	
	private Window mainWindow;
	private Panel mainPanel;

    @Override
    public void init()
    {
  	
    	mainWindow = new Window("Filer " + VERSION);	
    	
		try {
			service.importDataToDatabase("C:/dev/workspace/filer-services/database_export.xml");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

but when I run mvn:tomcat run, it gives me this:


C:\dev\workspace\filer-ui-vaadin>mvn tomcat:run
[INFO]
 Scanning for projects...
[INFO]
 ------------------------------------------------------------------------
[INFO]
 Building Vaadin Web Application
[INFO]
    task-segment: [tomcat:run]

[INFO]
 ------------------------------------------------------------------------
[INFO]
 Preparing tomcat:run
[INFO]
 [aspectj:compile {execution: default}]

[WARNING]
 bad version number found in C:\Documents and Settings\kj\.m2\repositor
y\org\aspectj\aspectjrt\1.6.1\aspectjrt-1.6.1.jar expected 1.6.3 found 1.6.1
[INFO]
 [resources:resources {execution: default-resources}]

[INFO]
 Using 'UTF-8' encoding to copy filtered resources.
[INFO]
 skip non existing resourceDirectory C:\dev\workspace\filer-ui-vaadin\src\
main\resources
[INFO]
 [compiler:compile {execution: default-compile}]

[INFO]
 Nothing to compile - all classes are up to date
[INFO]
 [tomcat:run {execution: default-cli}]

[INFO]
 Running war on http://localhost:8080/filer-ui-vaadin
[INFO]
 Using existing Tomcat server configuration at C:\dev\workspace\filer-ui-v
aadin\target\tomcat
14.7.2010 21:34:43 org.apache.catalina.startup.Embedded start
INFO: Starting tomcat server
14.7.2010 21:34:43 org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.26
14.7.2010 21:34:44 org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
- Root WebApplicationContext: initialization started
- Refreshing org.springframework.web.context.support.XmlWebApplicationContext@2c
5444: display name [Root WebApplicationContext]
; startup date [Wed Jul 14 21:34:
44 EEST 2010]; root of context hierarchy
- Loaded 0 bean definitions from location pattern [classpath*:context.xml]

- Bean factory for application context [org.springframework.web.context.support.
XmlWebApplicationContext@2c5444]: org.springframework.beans.factory.support.Defa
ultListableBeanFactory@1e45e3
- 0 beans defined in org.springframework.web.context.support.XmlWebApplicationCo
ntext@2c5444: display name [Root WebApplicationContext]
; startup date [Wed Jul 1
4 21:34:44 EEST 2010]; root of context hierarchy
- Unable to locate MessageSource with name 'messageSource': using default [org.s
pringframework.context.support.DelegatingMessageSource@13c1b69]
- Unable to locate ApplicationEventMulticaster with name 'applicationEventMultic
aster': using default [org.springframework.context.event.SimpleApplicationEventM
ulticaster@1263b07]
- Unable to locate ThemeSource with name 'themeSource': using default [org.sprin
gframework.ui.context.support.ResourceBundleThemeSource@cf7fda]
- Pre-instantiating singletons in org.springframework.beans.factory.support.Defa
ultListableBeanFactory@1e45e3: defining beans []; root of factory hierarchy
- Published root WebApplicationContext as ServletContext attribute with name [or
g.springframework.web.context.WebApplicationContext.ROOT]
- Root WebApplicationContext: initialization completed in 172 ms
14.7.2010 21:34:44 org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
14.7.2010 21:34:44 org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080

And when I start the application in browser it throws a null pointer exception from the FilerApplication class from that row where it first time uses the filerService.

It seems to me that my injection does not work so can someone tell me what I’m missing or have configured wrong??

Thanks in advance!!

I am not a Spring expert - maybe someone who knows Spring better can correct/expand on what I write - but I’ll try to guess what might be wrong.

At least with Spring 2.5 and later, I believe at least the last two lines are redundant when using
context:annotation-config
(and at least the first one is redundant, maybe both, when using
context:spring-configured
). They are still in the wiki example, probably as a remnant of the older configuration.

Out of these, you probably only need
context:component-scan
and one of
context:spring-configured
or
context:annotation-config
.

Where is your context.xml? If it is e.g. in META-INF/spring/, ContextLoaderListener in the web container probably won’t find it without you explicitly giving the path (e.g. classpath*:META-INF/spring/context.xml) - with your configuration, it is probably only looking for it in WEB-INF/context.xml and some other classpath root locations.

Note that you might also want to have a Spring META-INF/spring/applicationContext.xml for some other server-side configuration.

Thanks for your answer Henry!

Seems that I forgot to add to my initial post that it is a maven based project created with vaadin-clean-artifact.

And my spring dependencies are all versioned 2.5.6.

I’m not sure where my context.xml should be. Now it is in /src/main/webapp/META-INF/spring/context.xml
and I changed my web.xml to:


<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:META-INF/spring/context.xml</param-value>
  </context-param>

Still it says that “loaded 0 beans definitions”.
and couple of rows later “0 beans defined”.

It seems that it has something to do with BeanFactory because this it what I get when I try to start the application in browser:


- BeanFactory has not been set on BeanConfigurerSupport: Make sure this configur
er runs in a Spring container. Unable to configure bean of type [com.collapsux.f
iler.ui.FilerApplication]. Proceeding without injection.
java.lang.NullPointerException
        at com.collapsux.filer.ui.FilerApplication.init(FilerApplication.java:41
)

That NullPointerException just follows from the fact that no injection has been made.
I just don’t know what that BeanFactory message means…

Might be easier to give an example of something that works, so here is a complete Maven project using Spring 3.0.3, Hibernate (not really used - just dependencies, configuration etc.), AspectJ and injection with @Configurable and @Autowired into a Vaadin window. You can then start to take this apart if you want to dig deeper.

To test, run
mvn tomcat:run
and go to http://localhost:8080/myapp .

There are probably some unnecessary dependencies in the pom.xml, and it does not include the Vaadin widgetset related sections, which you might want to copy from your pom.xml .
11351.zip (10.2 KB)

Why can’t I see any attachements? I really want this example…

I’m no expert in spring, but I work so
class spring vaadin


mport java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;

import javax.servlet.ServletContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import  com.vaadin.*;
import com.vaadin.terminal.gwt.server.WebApplicationContext;

@SuppressWarnings("serial")
public class SpringControlador implements Serializable {
	
    

	
	private ApplicationContext context;

    public SpringControlador(Application  application) {
        ServletContext servletContext = 
                ((WebApplicationContext) application.getContext())
                .getHttpSession().getServletContext();
        context = WebApplicationContextUtils.
                getRequiredWebApplicationContext(servletContext);
    }

    public Object getBean(final String beanRef) {
        return context.getBean(beanRef);
    }

	 
}

my application get bean spring



ctx = new SpringControlador(this);
		controlDominio = (ControladorDominio) ctx.getBean("controladorDominio");
		controlDispositivo = (ControladorDispositivo) ctx
				.getBean("controladorDispositivo");

class control



public class ControladorDominio {

	
	private ControladorInventario controladorInventario;
	
	public ControladorInventario getControladorInventario() {
		return controladorInventario;
	}
       .....................
	

my control


..........

public class ControladorInventario  {

        private ServicioRegion servicioRegion;
	
	public ControladorInventario(){
		
	}
	
	
	public void setServicioRegion(ServicioRegion servicioRegion) {
		this.servicioRegion = servicioRegion;
	}

	public ServicioRegion getServicioRegion() {
		return servicioRegion;
	}

..................

my service


public class ServicioRegion implements Serializable{

	
	private RegionDAO regionDAO;
	
	public RegionDAO getRegionDAO() {
		return regionDAO;
	}
	
	public void setRegionDAO(RegionDAO regionDAO) {
		this.regionDAO = regionDAO;
	}

	//all operation my classs
	public List<Region> getListaRegion() throws ExcepcionDao {
		return regionDAO.findAll();
	}
...........

my DAO


SqlMapClientTemplate templateSpring = this.getSqlMapClientTemplate();
	public static Log logger = LogFactory.getFactory().getInstance(
			RegionDAO.class);
	
	@Override
	public int insert(Region item) throws ExcepcionDao {
		// TODO Auto-generated method stub
		try {
			Integer key = (Integer) templateSpring.insert("insertRegion", item);
			return key;
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			throw new ExcepcionDao(e.getMessage());

		}
	}
....
ALL OPERATION 

MY MAP


<sqlMap namespace="Region">

	<typeAlias type="com.gendarmeria.inventarioinformatico.dominio.Region"
		alias="region" />
	<resultMap id="resultRegion" class="region">
		<result property="idRegion" column="id" />
		<result property="nombre" column="nombre" />
		<result property="sigla" column="sigla" />
	</resultMap>
	<insert id="insertRegion" parameterClass="region">
		<![CDATA[ 
  			INSERT 
  				INTO region(nombre,sigla) 
  			VALUES
  				(#nombre#,#sigla#)
		]]>
		<selectKey resultClass="int">
		 <![CDATA[ 
  		 	SELECT LAST_INSERT_ID()
		]]>
		</selectKey>
	</insert>
ALL OPERATION SQL HERE
............

MY WEB XML


<?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>InventarioInformaticoGendarmeria</display-name>
	<context-param>
		<description>
		Vaadin production mode</description>
		<param-name>productionMode</param-name>
		<param-value>false</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:applicationContext*.xml</param-value>
	</context-param>
	<servlet>
all parmam vaadin HERE
.................

MY CONTEXT SPRING


<?xml version="1.0" encoding="UTF-8"?>

<!-- Beans_______________________________________________ -->

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
	 http://www.springframework.org/schema/beans 
	 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
     http://www.springframework.org/schema/aop 
     http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
	 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">

	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:jdbc.properties" />
	</bean>

	<!-- data Source_____________________________________________________________________ -->


	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${xxxxxxxxxxxx}" />
		<property name="password" value="${xxxxxxxxxxxxxx}" />
	</bean>

	<!-- Transaccion Manager______________________________________________________________ -->

	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>


	<tx:annotation-driven transaction-manager="transactionManager" />
	<context:annotation-config />

     dependency injection HERE

<bean id="servicioRegion"
		class="XXXXXXXXXXXXXXXXXXXXX">
		<property name="regionDAO">
			<ref bean="beanRegionDAO" />
		</property>
	</bean>
...........................................

   

work fine

Henri, can I use this to Autowire a Service ou Repository(DAO) ?

@Configurable works perfectly with @Autowired in any class on which the annotation is applied, when you want or have to to instantiate beans with “new”. This actually defines a new bean with name like class name with the annotation applied and scope “prototype”.

Usually you will want your services to be singletons, and use it for example like this:


@Repository
public class MapService
{

    @PersistenceContext(unitName = "ns")
    private EntityManager em;
...
}

@Configurable(preConstruction = true)
public class MapComponent extends CustomComponent
{
	/**
	 * Service implementing data access for map objects
	 */	
	@Autowired
	private MapService mapService;
....
}	

How would you like to use @Configurable?

BTW, one new feature of Spring 3.1 which I just found out is cache abstraction module, and it’s @Cacheable annotation.
It adds caching of method execution results. Just add @Cacheable(value = “cache_name”) as method-level annotation and

<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
		<property name="caches">
			<set>
				<bean
					class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
					p:name="cache_name" />
			</set>
		</property>
	</bean>

	<cache:annotation-driven mode="aspectj" />