Spring CrudRepository throws org.hibernate.LazyInitializationException - spring

i got a problem by using CrudRepository. Example: i have two entities, entity A has a collection of entity B.
class A {
int id;
int name;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
Set<B> bs;
// getters and setters
}
class B {
int id;
int name;
#ManyToOne(mappedBy="bs")
A a;
// getters and setters
}
then i got 2 repositories.
class ARepository extends CrudRepository<A, int>{}
class BRepository extends CrudRepository<B, int>{}
but when i got this, i got a org.hibernate.LazyInitializationException, how can i avoid this?
#Service
#Transactional(readOnly=true)
class ServiceImpl implements Service {
#Resource ARepository ar;
#Override
A a = ar.findOne(int id);
}
here is the applicationContext.xml:
<jpa:repositories base-package="com.myproject.repository" />
<context:component-scan base-package="com.myproject.*" />
<context:annotation-config />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="keep-apm" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="database" value="POSTGRESQL"/>
<property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect"/>
</bean>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="username" value="root" />
<property name="password" value="root" />
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://127.0.0.1:5432/db" />
</bean>
<bean id="sessionFactory" factory-bean="entityManagerFactory" factory-method="getSessionFactory">
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
here is the web.xml
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>com.myproject.util.LogLocator</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
a.bs(the collection) would not be loaded, and always throw out a org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: no session or session was closed
Thank you in advance!!

You need to use start a transaction, preferably through Spring's Declarative Transaction Management.
In most cases:
define a TransactionManager in your XML
add this to your XML <tx:annotation-driven />
annotate your service method with #Transactional
You can find a sample setup in section Using #Transactional

Here is the solution:
i can not access the object on my web layer, i should access the lazy loading objects in service layer, which should be in a transaction.

Related

Why i am getting a "1 bean exception" [duplicate]

This question already has an answer here:
What is a NoSuchBeanDefinitionException and how do I fix it?
(1 answer)
Closed 2 years ago.
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.home.dao.ProductDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
package com.home.dao;
#Repository
#Transactional
#Service
public class ProductDao implements proDaoInterface{
#Autowired
private SessionFactory sessionFactory;
public void addProduct(ProductModel product)
{
Session session= sessionFactory.getCurrentSession();
session.saveOrUpdate(product);
session.flush();
}
public ProductModel getProductByID(String ID)
{
Session session = sessionFactory.getCurrentSession();
ProductModel product = (ProductModel)session.get(ProductModel.class,ID);
session.flush();
return product;
}
#SuppressWarnings("unchecked")
public List<ProductModel> getProductList()
{
Session session= sessionFactory.getCurrentSession();
List<ProductModel> listProduct;
listProduct = session.createQuery("from ProductModel").getResultList();
session.flush();
return listProduct;
}
public void deleteProuct(String ID)
{
Session session = sessionFactory.getCurrentSession();
session.delete(getProductByID(ID));
session.flush();
}
}
controller class
#EnableWebMvc
#Controller
public class homeController {
#Autowired
private ProductDao dao;
#RequestMapping("/test")
public String home(Model model) {
List<ProductModel> productList = dao.getProductList();
model.addAttribute("productList", productList);
return "home";
}
#RequestMapping("/view/{productID}")
public String viewProduct(#PathVariable String productID, Model model) throws IOException {
ProductModel product = dao.getProductByID(productID);
model.addAttribute(product);
return "viewProduct";
}
}
Spring Configuration file
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url"
value="jdbc:oracle:thin:#localhost:1521:xe"></property>
<property name="username" value="system"></property>
<property name="password" value="admin"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hbm2ddl.auto">update</prop>
<prop key="dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="connection.pool_size">1</prop>
<prop key="show_sql">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.home.controllers</value>
<value>com.home.dao</value>
<value>com.home.model</value>
</list>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
Dispatcher -Servlet.xml
<context:component-scan base-package="com.home.controllers"></context:component-scan>
<mvc:annotation-driven/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
<mvc:resources mapping="/images/**" location="/WEB-INF/resources/images/" />
<mvc:resources mapping="/css/**" location="/WEB-INF/resources/css/" />
<mvc:resources mapping="/fonts/**" location="/WEB-INF/resources/fonts/" />
<mvc:resources mapping="/js/**" location="/WEB-INF/resources/js/" />
<mvc:resources mapping="/view/**" location="/view/" />
<tx:annotation-driven />
</beans>
web
<display-name>Product</display-name>
<listener>
<listener-class>
*org.springframework.web.context.ContextLoaderListener*
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/ApplicationConfig.xml,
/WEB-INF/DispatcherServlet.xml
</param-value>
</context-param>
<servlet>
<servlet-name>dad-frontController</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dad-frontController</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I believe your error is coming in fact you are restricting your component scan on dispatcher-servlet.xml.
Change the following:
<context:component-scan base-package="com.home.controllers"></context:component-scan>
To:
<context:component-scan base-package="com.home.*"></context:component-scan>
Checkout the official doc: https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-annotation-config
One more thing, your ProductDao has #Service and #Repository. Both say the same to Spring, so leave only #Repository.
Besides that, I would advise you to use Spring Boot, or, make those configurations via programmatically, it's way more clear =)

use spring in vaadin

i want to use spring in vaadin
it's my config:
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<servlet>
<servlet-name>VaadinApplicationServlet</servlet-name>
<servlet-class>com.vaadin.server.VaadinServlet</servlet-class>
<init-param>
<param-name>UI</param-name>
<param-value>com.MyUI</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>VaadinApplicationServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
applicationContext.xml
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/Activiti"/>
<property name="username" value="postgres"/>
<property name="password" value="10"/>
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="processEngineConfiguration" class="org.activiti.spring.SpringProcessEngineConfiguration">
<property name="databaseType" value="postgres"/>
<property name="dataSource" ref="dataSource"/>
<property name="transactionManager" ref="transactionManager"/>
<property name="databaseSchemaUpdate" value="true"/>
<property name="deploymentResources"
value="classpath* : #{Init.path_Process}"/>
<property name="history" value="audit"/>
<property name="jobExecutorActivate" value="false"/>
</bean>
<bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean">
<property name="processEngineConfiguration" ref="processEngineConfiguration"/>
</bean>
<bean id="repositoryService" factory-bean="processEngine"
factory-method="getRepositoryService"/>
<bean id="runtimeService" factory-bean="processEngine"
factory-method="getRuntimeService"/>
<bean id="taskService" factory-bean="processEngine"
factory-method="getTaskService"/>
<bean id="historyService" factory-bean="processEngine"
factory-method="getHistoryService"/>
<bean id="managementService" factory-bean="processEngine"
factory-method="getManagementService"/>
<bean id="formService" factory-bean="processEngine"
factory-method="getFormService"/>
<bean id="identityService" factory-bean="processEngine"
factory-method="getIdentityService"/>
<bean id="Init" class="util.Init"/>
<context:annotation-config/>
<context:component-scan base-package="com"/>
<context:spring-configured/>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
in MyUI class:
#java
#Component
#Configurable
public class MyUI extends UI {
protected void init(VaadinRequest vaadinRequest) {
...
#Autowired
private IdentityService identityService;
...
}}
this config work in junit and Ok!
but
when run in vaadin and tomcat , java.lang.NullPointerException error for identityService
where is my problem?
thanks
com.MyUI is created by the Vaadin servlet and that servlet does not know about Spring. What's happening is that your UI instance is created by reflection and isn't a Spring managed bean.
You need to use a Vaadin plugin that integrates with Spring. Please check the vaadin4spring project for more details.
Maybe you should update the class to org.vaadin.spring.servlet.SpringAwareVaadinServlet?
Try to autowire your bean explicite (e.g. in the constructor):
if (VaadinServlet.getCurrent() != null) {
try {
WebApplicationContextUtils
.getRequiredWebApplicationContext(VaadinServlet.getCurrent().getServletContext())
.getAutowireCapableBeanFactory().autowireBean(this);
} catch (BeansException e) {
LOG.error("Could not inject beans!" + this.getClass(), e); //$NON-NLS-1$
}
}
You may use ru.xpoft.vaadin.SpringVaadinServlet, check Vaadin website-addons
<servlet>
<servlet-name>MyCustom Application</servlet-name>
<servlet-class>ru.xpoft.vaadin.SpringVaadinServlet</servlet-class> ...............

hibernate sessionFactory not found but bean loaded

I've searched internet and debugged for a couple of hours but i'm stuck on finding whats wrong.
I have the follwng webapplication setup:
Jetty 8.1.0.v20120127
Spring-orm 3.1.2.RELEASE
Spring-web 3.1.2.RELEASE
Hibernate-core 4.1.7-final
In web.xml defined via sessionFactoryBeanName init-param: hibernateSessionFactory
While application starts no errors and shows the following:
XmlWebApplicationContext: loads a few beans from applicationContext.xml
ClassPathXmlApplicationContext: loads a few beans from applicationContext-hibernate.xml (also hibernateSessionFactory)
When loading a page (request) OpenSessionInViewFilter gets active and gives the following:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'hibernateSessionFactory' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:277)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1102)
at org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.lookupSessionFactory(OpenSessionInViewFilter.java:156)
at org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.lookupSessionFactory(OpenSessionInViewFilter.java:141)
at org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:105)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1336)
at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:172)
at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:267)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1336)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:483)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:521)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:233)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1065)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:412)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:192)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:999)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:250)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:149)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:111)
at org.eclipse.jetty.server.Server.handle(Server.java:351)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:451)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:916)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:634)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:230)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:76)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:609)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:45)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:599)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:534)
at java.lang.Thread.run(Thread.java:722)
While debugging on DefaultListableBeanFactory.java:553 the beanDefinitionMap shows a keyset with only the beans loaded with XmlWebApplicationContext. Thus none of the beans from the file applicationContext-hibernate.xml are shown.
bean definition (A break point on one of the setters of LocalSessionFactoryBean shows me that the bean is created):
<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocations" ref="hibernateConfigLocations"/>
<property name="dataSource" ref="hibernateDatasource"/>
<property name="namingStrategy" ref="hibernateNamingStrategy"/>
<property name="hibernateProperties" ref="hibernateProperties"/>
I was expecting to find all beans from both XmlWebApplicationContext and the ClassPathXmlApplicationContext. Can anybody tell what is causing my problem and please let me know when missing any information on finding the problem?
web.xml:
<display-name>webshop-cms</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>configuration</param-name>
<param-value>deployment</param-value>
</context-param>
<filter>
<filter-name>webshop-cms</filter-name>
<filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
<init-param>
<param-name>applicationClassName</param-name>
<param-value>nl.name.webshop.cms.CmsApplication</param-value>
</init-param>
<init-param>
<param-name>ignorePaths</param-name>
<param-value>/assets</param-value>
</init-param>
</filter>
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>hibernateSessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>webshop-cms</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
applicationContext.xml:
<context:component-scan base-package="nl.name.webshop.model" />
<context:component-scan base-package="nl.name.webshop.service" />
<context:component-scan base-package="nl.name.webshop.dao" />
<bean id="webshop.context" class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg>
<list>
<value>classpath:applicationContext-hibernate.xml</value>
</list>
</constructor-arg>
</bean>
applicationContext-hibernate.xml:
<bean id="hibernateNamingStrategy" class="org.hibernate.cfg.DefaultComponentSafeNamingStrategy" />
<bean id="hibernateConfigLocations" class="java.util.ArrayList">
<constructor-arg>
<list>
<value>classpath:hibernate.cfg.xml</value>
</list>
</constructor-arg>
</bean>
<bean id="jndiDatasourceName" class="java.lang.String">
<constructor-arg value="java:comp/env/jdbc/webshop"/>
</bean>
<jee:jndi-lookup id="hibernateConfig" jndi-name="jdbc/webshop-hibernate-config"/>
<jee:jndi-lookup id="hibernateDatasource" jndi-name="jdbc/webshop-datasource"/>
<bean id="hibernatePropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties" ref="hibernateConfig"/>
</bean>
<bean id="hibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocations" ref="hibernateConfigLocations"/>
<property name="dataSource" ref="hibernateDatasource"/>
<property name="namingStrategy" ref="hibernateNamingStrategy"/>
<property name="hibernateProperties" ref="hibernateProperties"/>
</bean>
Shouldn't the definition of your bean be:
<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
i.e. use id attribute instead of name.
[Edit]
Actually, is there a reason to load the applicationContext-hibernate.xml file this way:
<bean id="webshop.context" class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg>
<list>
<value>classpath:applicationContext-hibernate.xml</value>
</list>
</constructor-arg>
</bean>
I think you could simply have the following in applicationContext.xml:
<import resource="/path/relative/to/application/context/applicationContext-hibernate.xml"/>

Spring MVC:noHandlerFound

I am doing sample Spring mvc with Mybatis+Spring 3+Tomcat+Eclipse Indigo I got this problem
What's wrong? Any kind of advice for successful run this project. Previous problem was clear and Run this error message
org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringMVC/] in DispatcherServlet with name 'spring'
My web.xml here
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/servlet.xml
/WEB-INF/app.xml
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
My servlet.xml is
<context:annotation-config />
<context:component-scan base-package="logen.board.controller" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
app.xml is here
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:logen/board/dao/BoardDao.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<bean id="BoardDao" class="logen.board.entity.BoardEntity"></bean>
and my controller
#Controller
public class Boardcontroller {
#Autowired
private SqlSession sql;
#Autowired
private BoardEntity bn;
#RequestMapping("/list.do")
private ModelAndView list(){
BoardDao dao = sql.getMapper(BoardDao.class);
ModelAndView mv = new ModelAndView();
mv.setViewName("jsp/index");
mv.addObject("list", dao.getList());
return mv;
}
}

Spring 3 MVC dispatcher xml and applicationContext xml

I am creating a Spring MVC application for the first time.
It seems like when I start up the server, the applicationContext.xml loads the first time even before I run any mvc controller; This is what I want.
BUT once I run a controller that is loaded with context:component-scan in the dispatcher.xml ....IT SEEMS that the applicationContext.xml gets loaded again...
Why is this happening and how do I disable this? I only want my applicationContext.xml to run once.
Right after I run a controller, I see the logs below...
ClassPathXmlA I org.springframework.context.support.AbstractApplicationContext prepareRefresh Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#65cb65cb: startup date [Tue Feb 15 16:29:21 EST 2011]; root of context hierarchy
XmlBeanDefini I org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions Loading XML bean definitions from class path resource [WEB-INF/applicationContext.xml]
I think this is also causing my jms DefaultMessageListenerContainer to be created twice...
thanks
xxxdispatcher-servlet.xml
<context:component-scan base-package="com.something.web" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:interceptors>
<bean class="com.something.SomeInterceptor" />
</mvc:interceptors>
<mvc:resources mapping="/js/**" location="/js/" />
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.Exception">common/error</prop>
</props>
</property>
<property name="warnLogCategory" value="abcdefg"/>
</bean>
applicationContext.xml
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/application.properties" />
</bean>
<!-- Local Data Holder -->
<bean id="propertyHolder" class="com.common.PropertyHolder">
<property name="baseURL" value="${url.base}" />
</bean>
<bean id="messageListener" class="com.something.SomeListener" />
<bean id="xxxDAO"
class="com.XXXDAOImpl"
scope="prototype">
<property name="dataSource" ref="dataSourceQA" />
</bean>
<bean id="xxxServiceTarget" class="com.XXXServiceImpl">
<property name="xxxDAO" ref="xxxDAO"/>
</bean>
<bean id="xxxService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="txManager"/>
<property name="target" ref="xxxServiceTarget"/>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
<!-- and this is the message listener container -->
<bean id="jmsContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="xxxCF" />
<property name="destination" ref="xxxInboundQueue" />
<property name="messageListener" ref="messageListener" />
</bean>
WEB.xml
<servlet>
<servlet-name>xxxdispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>xxxdispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
Controller
#Controller
public class XXXController {
#Autowired
private IXXXService xxxService;
#RequestMapping("/xxx")
public String xxxHandler() throws Exception {
return "xxxView";
}
Please remove ContextLoaderListener from your Web.xml I beleive this is the reason why your context is created twice.

Resources