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

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 =)

Related

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> ...............

get Null pointer Exception when try to access model class in dwr function

My SessionFactory object is #Autowired
package com.ravi.dao.daoImpl;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.ravi.dao.UserDao;
import com.ravi.model.User;
#Repository("userDao")
public class UserDaoImpl implements UserDao {
#Autowired
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public List<User> listUsers()
{
System.out.println("UserDaoImpl - listUsers");
return (List<User>) sessionFactory.getCurrentSession().createCriteria(User.class).list();
}
#Override
public void saveUser(User user)
{
System.out.println("UserDaoImpl - saveUser");
sessionFactory.getCurrentSession().saveOrUpdate(user);
}
#SuppressWarnings("unchecked")
#Override
public List<User> getUserByUserEmail(String userEmail)
{
System.out.println("UserDaoImpl - getUserByUserEmail");
return sessionFactory.getCurrentSession().createQuery("from User where userEmail=:userEmail").setString("userEmail",userEmail).list();
}
#SuppressWarnings("unchecked")
#Override
public List<User> validateLoginUser(String userEmail, String password)
{
System.out.println("userEmail -- "+userEmail+" password --"+password);
System.out.println("UserDaoImpl - validateLoginUser");
return sessionFactory.getCurrentSession().createQuery("from User where userEmail=:userEmail and password=:password").setString("userEmail", userEmail).setString("password",password).list();
}
}
i create on dwr function which is below.
package com.ravi.dwr;
import java.util.List;
import com.ravi.dao.daoImpl.UserDaoImpl;
import com.ravi.model.User;
public class ForgotPwd
{
public void sendMail(String EmailId)
{
System.out.println("DWR Called.");
UserDaoImpl userDaoImpl=new UserDaoImpl();
List<User> lstUser=userDaoImpl.getUserByUserEmail(EmailId);
User user=lstUser.get(0);
System.out.println("DWR Called.-- userEmail :"+user.getUserEmail());
}
}
when i want to try to print userEmail . null pointer exception is generated # return sessionFactory.getCurrentSession().createQuery("from User where userEmail=:userEmail").setString("userEmail",userEmail).list(); this point.
my spring-servlet.xml cofiguration.
<?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"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="com.ravi"/>
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<mvc:annotation-driven />
<bean id="jspViewResolver"
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>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<!-- <bean id="sessionFactory" -->
<!-- class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> -->
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.ravi.model.User</value>
<value>com.ravi.model.Language</value>
<value>com.ravi.model.Questions</value>
<value>com.ravi.model.QuestionOptions</value>
<value>com.ravi.model.Admin</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="SessionFactory" ref="sessionFactory" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
in my project i used Annotation. is there any way to get user model data in dwr function.
or is there any process which automatically initialized (inject) when i try to use DAO class)
i don't want to remove #Autowired annotation in sessionFactory object. so please suggest me the best way to access or configure dwr function. other way i tried without using #Autowired annotation but in that case i have to entry all bean class in my spring-servlet.xml and also configure. hibernate.cfg.xml file.
in my project i used Annotation. is there any way to get user model data in dwr function.
or is there any process which automatically initialized (inject) when i try to use DAO class)
here i explain whole process. thank you in advance.
below error is generated when i am try to access userDaoImpl function. it is error show that session factory object is not initialized.
on more time i cleared that this is DWR function. which try to access sessionFactory instance.
without interacting controller.
UserLoginController --> showUserLogin
INFO (org.directwebremoting.log.startup:157) - Starting: DwrServlet v3.0.0-RC2-final-312 on Apache Tomcat/7.0.50 / JDK 1.7.0_10 from Oracle Corporation at `enter code here`/OnlineQuestion
DWR Called.
INFO (org.directwebremoting.log.accessLog:427) - Method execution failed:
java.lang.NullPointerException
at com.ravi.dwr.ForgotPwd.sendMail(ForgotPwd.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.directwebremoting.impl.CreatorModule$1.doFilter(CreatorModule.java:229)
at org.directwebremoting.impl.CreatorModule.executeMethod(CreatorModule.java:241)
at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:379)
at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:332)
at org.directwebremoting.dwrp.BaseCallHandler.handle(BaseCallHandler.java:104)
at org.directwebremoting.servlet.UrlProcessor.handle(UrlProcessor.java:120)
at org.directwebremoting.servlet.DwrServlet.doPost(DwrServlet.java:141)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChai
here i explain whole process. thank you in advance.
below error is generated when i am try to access userDaoImpl function. it is error show that session factory object is not initialized.
on more time i cleared that this is DWR function. which try to access sessionFactory instance.
without interacting controller.
Assuming you want to use Spring MVC with DWR, try following code:
WEB-INF/web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
WEB-INF/spring-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans
...
xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
...
http://www.directwebremoting.org/schema/spring-dwr
http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd">
<dwr:controller id="dwrController" />
<dwr:annotation-scan base-package="com.ravi.dwr" />
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="alwaysUseFullPath" value="true" />
<property name="mappings">
<props>
<prop key="/dwr/**/*">dwrController</prop>
</props>
</property>
</bean>
<context:component-scan base-package="com.ravi" />
...
</beans>
ForgotPwd.java
package com.ravi.dwr;
...
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
...
#RemoteProxy
public class ForgotPwd {
#Autowired
private UserDaoImpl userDaoImpl;
...
#RemoteMethod
public void sendMail(String EmailId) {
System.out.println("DWR Called.");
List<User> lstUser=userDaoImpl.getUserByUserEmail(EmailId);
...
}
...
}

Spring MVC controller mapping problems

I'm new to Spring MVC and trying to learn from some web tutorials and Spring's PetClinic. When I was just starting I was using some tutorials from some really old releases of Spring. I didn't know it at the time, so it has been a lot of back and an regroup attempts. I am having trouble with the way my test site finds the Controller classes. The site finds my index.jsp file and executes that just fine. But when I try to click on a link that maps to one the the Controller classes I get a page not found (404) error.
Everything compiles and deployes with no errors on JBoss EAP 6.1.
I'm attaching some of the snippets from my config files. Can somebody look at them and see what I'm doing wrong>
Web.xml snippet:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:resources/spring/core-config.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
the dispatcher servlet.xml snippet:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
<bean class="org.S2Me.MyHealth.controller.CustomMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.servlet.PageNotFound">notFound</prop>
<prop key="java.lang.Exception">failure</prop>
</props>
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
>
<property name="basename" value="/WEB-INF/messages" />
</bean>
the core-Servlet snippet:
<import resource="view-config.xml"/>
<context:component-scan base-package="org.S2Me.MyHealth.controller" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
<mvc:view-controller path="/" view-name="index" />
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="messages/messages" />
<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"
>
<property name="defaultErrorView" value="exception" />
<!-- results into 'WEB-INF/jsp/exception.jsp' -->
<property name="warnLogCategory" value="warn" />
</bean>
the view-Servlet snippet:
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"
>
<property name="contentNegotiationManager" ref="cnManager" />
<property name="viewResolvers">
<list>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
>
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean
class="org.springframework.web.servlet.view.BeanNameViewResolver" />
</list>
</property>
</bean>
<bean id="cnManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="true"/>
<property name="ignoreAcceptHeader" value="true"/>
<property name="defaultContentType" value="text/html"/>
<property name="mediaTypes">
<map>
<entry key="html" value="text/html" />
<entry key="xml" value="application/xml" />
<entry key="atom" value="application/atom+xml" />
</map>
</property>
</bean>
The index.jsp snippet:
<div class="navbar-inner">
<ul class="nav">
<li style="width: 100px;"><a href="<spring:url value="/" htmlEscape="true" />"><i class="icon-home"></i>
Home</a></li>
<li style="width: 130px;">
Login
</li>
</ul>
</div>
The Login Controller class:
package org.S2Me.MyHealth.controller;
import org.S2Me.MyHealth.server.LoginForm;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.validation.BindingResult;
import java.util.Map;
import javax.validation.Valid;
#Controller
#RequestMapping("/login")
public class LoginController
{
#SuppressWarnings({ "rawtypes", "unchecked" })
#RequestMapping(method = RequestMethod.GET)
public String showForm(Map model)
{
LoginForm loginForm = new LoginForm();
model.put("loginForm", loginForm);
return "loginform";
}
#RequestMapping(method = RequestMethod.POST)
public String processForm(#Valid LoginForm loginForm, BindingResult result,
Map model)
{
String userName = "UserName";
String password = "password";
if (result.hasErrors())
{
return "loginform";
}
loginForm = ( LoginForm) model.get("loginForm");
if (!loginForm.getUserName().equals(userName)
|| !loginForm.getPassword().equals(password))
{
return "loginform";
}
model.put("loginForm", loginForm);
return "loginsuccess";
}
}
Any syntax errors are my cutting and pasting like I said no error in compile or deployment, just 404 errors on navigation.
Any help would be appreciated. Thanks
Your configuration is ignoring the dispatcher-servlet.xml file.
Upon initialization of a DispatcherServlet, Spring MVC looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and creates the beans defined there, overriding the definitions of any beans defined with the same name in the global scope. Source: Spring Reference
One can override this by specifing an init-param with the name contextConfigLocation.
As you are specifing this parameter your dispatcher-servlet.xml is thus ignored and with that the configuration inside of it.

No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0:

I am using springframework 3.2 with jboss server 7.1 .
Trying to set up a simple spring app with jpa2(hibernate provider, mysql) and spring mvc.
I use a simple DAO which i inject with autowired annotation in the home controller.
This dao class simply has a field (em) for persistentContext to get injected, it coudlnt be more trivial, i dont use a persistence.xml since spring from version 3.1 and up does not need one.....note that packages are scanned properly
i have tried everything from other solutions posted in the web (including here)...
but i get this error:
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: com.stko.home.model.daos.UserDao
com.stko.home.controllers.HomeController.userDao; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'userDao': Injection of persistence
dependencies failed; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
unique bean of type [javax.persistence.EntityManagerFactory] is
defined: expected single bean but found 0:
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1120)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:598)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:661)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:517)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:458)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138)
javax.servlet.GenericServlet.init(GenericServlet.java:242)
org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50)
org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930)
java.lang.Thread.run(Thread.java:722)
my applicationContext.xml:
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mmydb"/>
<property name="username" value="user"/>
<property name="password" value="1234"/>
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan" value="com.stko.home.model.entities"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.show.sql">true</prop>
<prop key="hibernate.connection.charSet"> UTF-8</prop>
</props>
</property>
</bean>
<!-- tell spring to use annotation based congfigurations -->
<context:annotation-config />
<!-- scan for beans -->
<context:component-scan base-package="com.stko.home.model.daos"/>
<!-- to recognize persistnce annotations like PersistenceContext -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="databaseProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:database.properties"/>
</bean>
my servlet-context.xml:
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.stko.home"/>
my web.xml:
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
my userDao:
#Service("userDao")
#Repository
public class UserDao implements Serializable {
#PersistenceContext
private EntityManager em;
#Transactional
public void saveUser(User user) {
if(user!=null)
em.persist(user);
}
}
my entity class User:
#Entity
#Table(name = "user")
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "userid")
private Integer userid;
#Column(name="username")
private String username;
public User(){}
}
my typical home controller:
#Controller
public class HomeController {
.....
#Autowired
UserDao userDao;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
.....
User newUser = new User();
newUser.setName("blabla");
userDao.saveUser(newUser);
return "home";
}
}
Do you have a persistence.xml in which you have defined your persistence unit?
The issue most likely is this line in servlet-context.xml file:
<context:component-scan base-package="com.stko.home"/>
which is essentially trying to create your DAO once more in your Web application Context. You should just have a filter which only creates your controllers here, this way:
<context:component-scan base-package="com.stko.home">
<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation" />
</context:component-scan>
Try this
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
</bean>
Define the properties for your EMF bean, persistenceUnit should be the name you declare on persistence.xml

Spring CrudRepository throws org.hibernate.LazyInitializationException

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.

Resources