Error creating bean with name 'commodityClassDAO' defined in servlet spring beanContext resource!,在线急等!

06-07工作错误
实际开发常见错误
attempted to delete null:
现象:在页面中删除对象失败
原因:在DAO的remove方法中
&public void reomveSight(Long[] sightid) throws
SightException
for(int i=0;i&sightid.i++)
super.removeObject(TtourInfo***.class,sightid[i]);
绑定错了对象,导致attempted to delete null错误。
现象:删除的时候不能级联删除子表中的数据导致报外键引用的错误。
解决方法:sight景点与image图片是一对多的关系,sight的hbm.xml配置文件原来在配置图片时是:
&!-- bi-directional one-to-many association to TtourInfoImage
name="ttourInfoImages"
lazy="true"
inverse="true"
cascade="none"
&meta attribute="field-description"&
&&&&&&&&&&
@hibernate.set
&&&&&&&&&&&
lazy="true"
&&&&&&&&&&&
inverse="true"
&&&&&&&&&&&
cascade="none"
&&&&&&&&&&
@hibernate.collection-key
&&&&&&&&&&&
column="COMPANY"
&&&&&&&&&&
@hibernate.collection-one-to-many
&&&&&&&&&&&
class="com.strongit.tour.bo.TtourInfoImage"
&&&&&&&&&&&
&column name="SIGHTID" /&
&one-to-many
&&&&&&&&&&&
class="com.strongit.tour.bo.TtourInfoImage"
&!-- bi-directional one-to-many association to TtourInfoImage
name="ttourInfoImages"
lazy="true"
inverse="true"
cascade="all"
&meta attribute="field-description"&
&&&&&&&&&&
@hibernate.set
&&&&&&&&&&&
lazy="true"
&&&&&&&&&&&
inverse="true"
&&&&&&&&&&&
cascade="all"
&&&&&&&&&&
@hibernate.collection-key
&&&&&&&&&&&
column="COMPANY"
&&&&&&&&&&
@hibernate.collection-one-to-many
&&&&&&&&&&&
class="com.strongit.tour.bo.TtourInfoImage"
&&&&&&&&&&&
&column name="SIGHTID" /&
&one-to-many
&&&&&&&&&&&
class="com.strongit.tour.bo.TtourInfoImage"
就可以了。
dao配置文件错误
错误描述:
Error registering
bean with name
'tour.scenicArea.sceneryAreaDao'
&defined in ServletContext
[/WEB-INF/config_ext/applicationContext-tour-sceneryarea-dao.xml]:
&Bean class
com.strongit.tour.scenicArea.dao.impl.SceneryAreaDaoImpl]
nested exception is
java.lang.ClassNotFoundException:
com.strongit.tour.scenicArea.dao.impl.SceneryAreaDaoImpl
applicationContext-tour-sceneryarea-dao.xml&&
class="com.strongit.tour.scenicArea.dao.impl.SceneryAreaDaoImpl"
class="import
com.strongit.tour.scenicArea.dao.impl.SceneryAreaDaoImpl"
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name
'tour.service.isightService'
defined in ServletContext resource
[/WEB-INF/config_ext/applicationContext-tour-sight-service.xml]:
&Can't resolve reference to
'tour.service.sightService'
while setting property 'target';
nested exception is
org.springframework.beans.factory.BeanCreationException:
&Error creating bean with name
'tour.service.sightService'
&defined in ServletContext
[/WEB-INF/config_ext/applicationContext-tour-sight-service.xml]:
Error set nested exception is
org.springframework.beans.NotWritablePropertyException:
Invalid property 'sightDao' of bean class
[com.strongit.tour.scenicArea.service.impl.SightServiceImpl]:
Bean property 'sightDao' is not writable or has an
invalid setter method:
Does the parameter type of the setter match the
return type of the getter?
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'tour.service.sightService' defined in
ServletContext resource
[/WEB-INF/config_ext/applicationContext-tour-sight-service.xml]:
Error set nested exception is
org.springframework.beans.NotWritablePropertyException: Invalid
property 'sightDao' of bean class
[com.strongit.tour.scenicArea.service.impl.SightServiceImpl]: Bean
property 'sightDao' is not writable or has an invalid setter
method: Does the parameter type of the setter match the return type
of the getter?
org.springframework.beans.NotWritablePropertyException: Invalid
property 'sightDao' of bean class
[com.strongit.tour.scenicArea.service.impl.SightServiceImpl]: Bean
property 'sightDao' is not writable or has an invalid setter
method: Does the parameter type of the setter match the return type
of the getter?
在com.strongit.tour.scenicArea.service.impl.SightServiceImpl类中没有对sightDao添加set属性。
缺少&html:hidden
property="sceneryareaid"&&/html:hidden&来绑定id的值。
org.apache.jasper.JasperException:
&/member/tour/sceneryareamanage/sight_edit.jsp(121,7)
According to the TLD attribute property is mandatory for tag
错误原因:htmltext标记与input标记的属性混用
javax.servlet.ServletException:
&No bean named
'/tour/scenicArea/deleteSightAction' is defined:
错误原因:
在applicationcontext-tour-sight-action中删除的action配置的path
与struts-config-tour-sight中相应的删除配置不相同
FORM表单的上传的文件数组元素时报参数错误
错误提示:
IllegalArgumentException&&&&&&&&&
--argument type mismatch
解决方法:
在&html:form中加入enctype="multipart/form-data"
HQL语句时出错
景点与图片是一对多的关系,现在要从一的景点中找到相应的图片的所有信息。
在daoimpl中
&public List querySQLEx(String
SqlStr) throws SightException
return super.getHibernateTemplate().find(SqlStr);
&public TtourInfoImage
getImagePathToSight(Long sightid) throws SightException
& return (TtourInfoImage)
this.querySQLEx("select TtourInfoImage m where
m.ttourInfoSight.sightid="+sightid);
在删除的action的调用中
String msg="";
&& String []
sightid=request.getParameter("delid").split(",");
&&& String root
= getServletContext().getRealPath("/");
System.out.println(root);
&&& Long []
sightID=new Long[sightid.length];
fileList=new ArrayList();
&&& for(int
i=0;i&sightid.i++)
sightID[i]=Long.valueOf(sightid[i].trim());
//把图片对象放入临时保存图片的图片路径数组中
fileList.add(sightService.getImagePathToSight(sightID[i]).getImageFile());
System.out.println("原图="+sightService.getImagePathToSight(sightID[i]).getImageFile());
fileList.add(sightService.getImagePathToSight(sightID[i]).getImageBreviry());
System.out.println("缩略图="+sightService.getImagePathToSight(sightID[i]).getImageBreviry());
sightService.reomveSight(sightID);//先批量删除景点和与景点有关的图片表的数据
sightService.delImage(root,fileList);//再删除图片表中,与景点相关的图片
"景点删除成功!";
(Exception e)
System.out.println(e.getMessage());
(e.getMessage());
"对不起,在您删除的数据中已有数据被使用,无法删除!";
& catch (RuntimeException e)
e.printStackTrace();
msg="在删除景点的过程中出现意外错误!";
& request.setAttribute("msg",
return mapping.findForward("success");
nested exception is
org.springframework.beans.factory.BeanCreationException:
&Error creating bean with name
'modityService' defined in ServletContext
[/WEB-INF/config_user/applicationContext-tour-commodity-service.xml]:
nested exception is
org.springframework.beans.PropertyAccessExceptionsException:
&PropertyAccessExceptionsException
(1 errors);
nested propertyAccessExceptions are:
[org.springframework.beans.TypeMismatchException:
&Failed to convert property value
[com.modityManage.modityTypeDAOImpl]
&to required type
[com.modityManage.dao.ICommodityDAO]
for property 'commodityDAO']
org.springframework.beans.factory.BeanCreationException:
&Error creating bean with name
'modityService'
&defined in ServletContext
&[/WEB-INF/config_user/applicationContext-tour-commodity-service.xml]:
&Error setting property
nested exception is
org.springframework.beans.PropertyAccessExceptionsException:
&PropertyAccessExceptionsException
(1 errors); nested propertyAccessExceptions are:
&[org.springframework.beans.TypeMismatchException:
&Failed to convert property value
[com.modityManage.modityTypeDAOImpl]
&to required type
[com.modityManage.dao.ICommodityDAO]
&for property 'commodityDAO']
PropertyAccessExceptionsException (1 errors)
org.springframework.beans.TypeMismatchException:
&Failed to convert property value
[com.modityManage.modityTypeDAOImpl]
to required type
[com.modityManage.dao.ICommodityDAO]
&for property 'commodityDAO'
在dao配置文件中
class="com.modityManage.modityDAOImpl"
写成了class="com.modityManage.modityTypeDAOImpl"
将商品hbm.xml文件中图片的相关链接的cascode="none"改为"all"。
在&html:form&里的action写错了。
javax.servlet.ServletException:
Error creating bean with name
&'/tour/commodityManage/addCommodityAction'
&defined in ServletContext resource
[/WEB-INF/config_user/applicationContext-tour-commodity-action.xml]:
nested exception is
org.springframework.beans.NotWritablePropertyException:
Invalid property 'commodityService' of bean class
[com.modityManage.action.AddCommodityAction]:
Bean property 'commodityService' is not writable or has an
invalid setter method:
&Does the parameter type of the setter match
the return type of the getter?
在AddCommodityAction.do中少了commodityService的set方法
现象:加载工程时有绔绞欢之类的字样的错误,工程不能启动
解决方法:选中工程,选菜单下的Project下的Properties选项,
把字符编码改为UTF-8。
工程中出现没有编译成class文件时,选eclipe里的project的BuildAutomatically就行。
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。Put together Struts2, JPA, Hibernate and Spring
This weekend I played a bit with Struts2. Obviously my first thought was to put together “fellowship of the ring” ie Struts, Spring and Hibernate. Now, we have two ways for integrating Hibernate and I’ve chosen the Java Persistence Architecture approach, because is the latest trend in terms of persistence in the J2EE landscape.
Create your domain model
For the sake of simplicity I’ll take
a simple example that contains Books and Authors. A book has one or more authors while one author wrote one or more books. This looks like a many to many relationship and we want to be able to get, from one shoot, the book and its authors and for an author his entire list of books.
package org.bserban.shs.
import javax.persistence.*;
import java.util.L
@Table(name = "book")
public class Book {
@GeneratedValue
private String ISBN13;
private String ISBN10;
@ManyToMany(fetch = FetchType.EAGER)
private List&Author&
........................................
Author. java
package org.bserban.shs.
import javax.persistence.*;
import java.util.L
@Table(name = "author")
public class Author {
@GeneratedValue
private String firstN
private String lastN
@ManyToMany(mappedBy="authors",fetch = FetchType.EAGER)
private List&Book&
.......................................
As you see in the code snippets above, the many to many relationship was marked with @ManyToMany annotation. We specified that the many to many relationship is mapped by Author entity too. No need to create a persistence.xml or hibernate.cfg.xml files at this moment because the whole configuration will take place in the Spring files.
Create a DAOs
First of all create a generic DAO object to keep the reference to the EntityManager and avoid duplicate code in other DAOs.
package org.bserban.shs.
import javax.persistence.EntityM
import javax.persistence.PersistenceC
public abstract class GenericJPADAO&T, ID extends Serializable& {
private Class&T& persistentC
protected EntityM
@PersistenceContext
public void setEntityManager(EntityManager em) {
public EntityManager getEntityManager() {
public void save(T entity) {
getEntityManager().persist(entity);
public void delete(T entity) {
getEntityManager().remove(entity);
public T getById(Object id) {
return getEntityManager().find(persistentClass, id);
By making a generic DAO class using java generics we are avoiding casting and using the Object class as parameter, in this way our methods will always have the proper type for their operation. While this is very easy with simple application it can become more complicated, but don’t forget that now we are building bricks that will help us to build our house, for more complicated logic we just simply create a facade class that will use our bricks.
BookDAO.java and AuthorDAO.java
package org.bserban.shs.
import org.bserban.shs.model.A
public class AuthorDAO extends GenericJPADAO&Author,Integer& {
package org.bserban.shs.
import org.bserban.shs.model.B
public class BookDAO extends GenericJPADAO&Book,Integer&{
These classes are empty so far but specific methods will probably be added.
Create your service layer
I am going to build also a generic service similar with the generic DAO class. For this example I only need basic operations that can be easily made generic. All I need is to create a generic interface called GenericService and ask for a type. Note that while GenericService is an interface for the DAOs I’ve done an abstract class because I wanted to add code to methods.
package org.bserban.shs.
import java.util.L
public interface GenericService&T& {
T create(T entity);
void delete(T entity);
T update(T entity);
List&T& list(int page, int size);
Now, in the Services
classes we need to have also a reference to the specific DAO object for that type of service. I am going to create a dao field in each class and I am going to assume that somebody will set the dao to the correct value when the service will be used.
BookService.java and AuthorService.java, their structure is identically so i will list only one here:
package org.bserban.shs.
import org.bserban.shs.dao.AuthorDAO;
import org.bserban.shs.model.A
import java.util.L
public class AuthorService implements GenericService&Author& {
private AuthorDAO
public Author create(Author entity) {
dao.save(entity);
public void delete(Author entity) {
dao.delete(entity);
public Author update(Author entity) {
dao.save(entity);
public List&Author& list(int page, int size) {
return dao.list(page,size);
public AuthorDAO getDao() {
public void setDao(AuthorDAO dao) {
this.dao =
For the listing feature I simply added a new method in the DAOs for list, and it looks like this:
................
public List&Author& list(int page, int size) {
Query query = this.em.createQuery("from Author order by lastName,firstName");
query.setFirstResult((page - 1) * size);
query.setMaxResults(size);
return query.getResultList();
.................
public List&Book& list(int page, int size) {
Query query = this.em.createQuery("from Book order by title");
query.setFirstResult((page - 1) * size);
query.setMaxResults(size);
return query.getResultList();
..................
Create the Actions
The actions are part of the controller and they need to validate data and to provide error handling before calling the service layer. One characteristic of putting together the Spring and Struts2 is that the dependency injection is done via a constructor argument. You could do it also with setters and getters but this would expose your service class to the exterior. One could call your action via HTTP by providing a parameter with the same name of your service class which will result into an unpredictable behavior, most probably an error.
In the actions I am going to have three fields, the first is the Service reference, the second is the list of model object and the third is a solo entity used for create, update, delete.
I will only list one Action class because they are pretty similar:
public class AuthorAction extends FrontendAction {
private GenericService&Author&
private List&Author&
public AuthorAction(GenericService&Author& service) {
this.service =
public String list() {
authors=service.list(page, size);
return SUCCESS;
public String update() {
service.update(author);
return SUCCESS;
public String create() {
service.create(author);
return SUCCESS;
public String delete() {
service.delete(author);
return SUCCESS;
......................................
I have created a FrontendAction to put the page and size parameters, since they are a common feature of both actions.
Similar, you can put here other attributes that are common for the all actions.
Now lets add our actions into struts.xml file and start to configure the Spring support. I have chosen the extension of our actions to be *.html. I also want to set the Struts2 into dev mode to debug the application if necessary. For IOC Struts2 has a property called objectFactory which let’s you to specify what is your IOC container, i set this to “spring” values. The views will be written as Freemarker templates which I consider to be a powerful template engine.
&constant name="struts.devMode" value="true"/&
&constant name="struts.action.extension" value="html"/&
&constant name="struts.objectFactory" value="spring"/&
&constant name="struts.ui.theme" value="simple"/&
&constant name="struts.ui.templateSuffix" value="ftl"/&
&constant name="struts.configuration.xml.reload" value="true"/&
Now we need to declare our actions, I’ve decided to create different name space for each action which means that the http calls will look like this: /books/…..
/authors/…..
&package name="books" namespace="/books" extends="struts-default"&
&action name="list" class="bookAction" method="list"&
&result name="success" type="freemarker"&/WEB-INF/pages/books/list.ftl&/result&
&/package&
&package name="authors" namespace="/authors" extends="struts-default"&
&action name="list" class="authorAction" method="list"&
&result name="success" type="freemarker"&/WEB-INF/pages/authors/list.ftl&/result&
&/package&
For the purpose of demonstration I am providing only the listing capability, I let you code the rest. So I need to create two templates to list the entities, they are done in the same way so i am pasting only the author’s list page:
&link media="screen" type="text/css" href="${base}/resources/css/style.css" rel="stylesheet"&
&table class="listing"&
&tr&&td class="hed" colspan="3"&List of authors&/td&&/tr&
&th&First Name&/th&
&th&Last Name&/th&
&th&Books&/th&
[#list authors as author]
&tr [#if author_index%2 = 0]class="bg"[/#if]&
&td&${author.firstName!''}&/td&
&td&${author.lastName!''}&/td&
&td&[#if author.books??][#list author.books as book] ${book.title}[#if book_has_next],[/#if][/#list][/#if]&/td&
Glue the code with Spring
This example uses Spring 2.5.5 version. I am going to separate the configuration files in two, one is for generic configuration for JPA and transactions and the second will contain our classes glued together.
My applicationContext.xml
Declare the JPA support
&bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /&
Now declare the EntityManager bean
&bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&
&property name="dataSource" ref="dataSource" /&
&property name="jpaVendorAdapter"&
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"&
&property name="database" value="MYSQL" /&
&property name="showSql" value="true" /&
&/property&
The data source used by EntityManager bean
&bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"&
&property name="driverClassName" value="com.mysql.jdbc.Driver" /&
&property name="url" value="jdbc:mysql://localhost/example" /&
&property name="username" value="example" /&
&property name="password" value="example" /&
Now I need to configure the transaction manager for my classes and obviously I am going to use the one that supports annotations. The era for declarative transaction configuration has long gone.
&bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager"&
&property name="entityManagerFactory" ref="entityManagerFactory" /&
&tx:annotation-driven transaction-manager="transactionManager" /&
Let’s not forgot our objects, let’s tell Spring where is our application specific configuration file
&import resource="exampleContext.xml"/&
Now, all I need is to glue my classes together, basically our DAOs need the JPA beans, the Services need our DAOs and Struts Actions need our Services.
exampleContext.xml will contain the followings:
&!-- daos --&
&bean id="authorDao" class="org.bserban.shs.dao.AuthorDAO"/&
&bean id="bookDAO" class="org.bserban.shs.dao.BookDAO"/&
&!-- services --&
&bean id="authorService" class="org.bserban.shs.service.AuthorService"&
&property name="dao" ref="authorDao"/&
&bean id="bookService" class="org.bserban.shs.service.BookService"&
&property name="dao" ref="bookDAO"/&
&!-- action --&
&bean id="authorAction" scope="prototype" class="org.bserban.shs.action.AuthorAction"&
&constructor-arg ref="authorService"/&
&bean id="bookAction" scope="prototype" class="org.bserban.shs.action.BookAction"&
&constructor-arg ref="bookService"/&
Now add the transaction support to our service classes. I simply need to put the @Transactional annotation at class level which means that all method from that class support transactions.
import org.springframework.transaction.annotation.T
@Transactional
public class BookService implements GenericService&Book& {
.........................
I am going to configure also the web.xml file, where I’ll put the configuration for Struts and for Spring.
&context-param&
&param-name&contextConfigLocation&/param-name&
&param-value&/WEB-INF/applicationContext.xml&/param-value&
&/context-param&
&filter-name&struts2&/filter-name&
&filter-class&org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
&/filter-class&
&filter-mapping&
&filter-name&struts2&/filter-name&
&url-pattern&/*&/url-pattern&
&/filter-mapping&
&listener&
&listener-class&org.springframework.web.context.ContextLoaderListener&/listener-class&
&/listener&
Now all we need is to hit run and see if it is working. Also we are going to need some testing data.
Database tables
Putting this line &property name=”generateDdl” value=”true” /& into EntintyManagerFactory bean configuration will cause the generation of our database tables.
I just need to insert manually some sample data to be able to list them in the “list” pages.
Sample data:
INSERT INTO `author` (`id`,`firstName`,`lastName`,`blog`) VALUES
(1,'John','Doe','no blog'), (2,'Sam','Dune','no blog');
INSERT INTO `book` (`id`,`title`,`publisher`,`keywords`,`ISBN13`,`ISBN10`) VALUES
(1,'Some Random Title','The plublisher','random','','978-');
INSERT INTO `book_author` (`books_id`,`authors_id`) VALUES
Html Views
Let’s add a simple css file to give a decent look to our pages, all we need is to customize the table look&feel.
table.listing {
text-align:
font-family: Verdana, Geneva, Arial, Helvetica, sans-
font-weight:
font-size: 11
width: 280
background-color: #666;
border-collapse:
border-spacing: 0
table.listing td {
background-color: #CCC;
color: #000;
padding: 4
text-align: left;
border: 1px #
table.listing td.hed {
background-color: #666;
padding: 4
text-align: left;
border-bottom: 2px #
font-size: 12
font-weight:
End the result:
I hope I’ll have the time to continue this apps and introduce jQuery for simple actions like add/edit/delete/filter books and authors.
I’ll list here all the needed jars/frameworks for this sample application:
Hibernate 3.2.1 (+ deps)
archive-browsing-1.0.jar, this was needed by hibernate to work with JPA
hibernate-entity-manager-3.2.1.jar
mysql-connector-java-5.0.4.jar
jta-1.0.B.jar
persistence-api-1.0.jar
Spring 2.5.5 jar file
Struts 2.1.6 (+ deps)
struts2-spring-plugin.jar
Source code sample, you can downloaded from here}

我要回帖

更多关于 error creating bean 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信