- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试使用 Spring MVC 和 Hibernate 运行我的第一个 Web 应用程序,但我遇到了一些问题。
通用道:
@Repository
public abstract class GenericDao<T> implements GeneralDao<T> {
private Class<T> className;
protected GenericDao(Class<T> className) {
this.className = className;
}
@PersistenceContext
private EntityManager entityManager;
public EntityManager getEntityManager() {
return entityManager;
}
@Override
public void add(T object) {
try {
getEntityManager().persist(object);
} catch (HibernateException e) {
throw new DaoException(ErrorMessage.MESSAGE_ADD_ENTITY_FAIL, e);
}
}
@Override
public void update(T object) {
try {
getEntityManager().merge(object);
} catch (HibernateException e) {
throw new DaoException(ErrorMessage.MESSAGE_UPDATE_ENTITY_FAIL, e);
}
}
@Override
public void remove(T object) {
try {
getEntityManager().remove(object);
} catch (HibernateException e) {
throw new DaoException(ErrorMessage.MESSAGE_REMOVE_ENTITY_FAIL, e);
}
}
@Override
public T getById(int id) {
try {
return getEntityManager().find(this.className, id);
} catch (HibernateException e) {
throw new DaoException(ErrorMessage.MESSAGE_GET_BY_ID_ENTITY_FAIL, e);
}
}
public abstract List<T> getAll() throws DaoException;
}
用户道.java:
@Repository
public class UserDao extends GenericDao<User> {
private final static String USER_LOGIN = "login";
private final static String USER_PASSWORD = "password";
private UserDao() {
super(User.class);
}
@Override
public List<User> getAll() {
List<User> userList;
try {
userList = getEntityManager().createQuery(Statement.GET_ALL_USERS).getResultList();
} catch (HibernateException e) {
throw new DaoException(ErrorMessage.MESSAGE_GET_ALL_ENTITY_FAIL, e);
}
return userList;
}
public List<User> getByLoginAndPassword(String userLogin, String userPassword) {
CriteriaQuery<User> criteriaQuery;
try {
CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
criteriaQuery = criteriaBuilder.createQuery(User.class);
Root<User> userRoot = criteriaQuery.from(User.class);
criteriaQuery.select(userRoot);
criteriaQuery.where(
criteriaBuilder.equal(userRoot.get(USER_LOGIN), userLogin),
criteriaBuilder.equal(userRoot.get(USER_PASSWORD), userPassword)
);
} catch (HibernateException e) {
throw new DaoException(ErrorMessage.MESSAGE_GET_ENTITY_BY_LOGIN_AND_PASSWORD_FAIL, e);
}
return getEntityManager().createQuery(criteriaQuery).getResultList();
}
}
通用服务.java:
@Service
public abstract class GenericService<T> implements GeneralService<T> {
private static Logger logger = Logger.getLogger(GenericService.class);
@Autowired
private GenericDao<T> dao;
@Transactional
@Override
public void add(T object) throws ServiceException {
try {
dao.add(object);
} catch (DaoException e) {
logger.debug(e);
throw new ServiceException(e.getMessage());
}
}
@Transactional
@Override
public void update(T object) throws ServiceException {
try {
dao.update(object);
} catch (DaoException e) {
logger.debug(e);
throw new ServiceException(e.getMessage());
}
}
@Transactional
@Override
public void remove(T object) throws ServiceException {
try {
dao.remove(object);
} catch (DaoException e) {
logger.debug(e);
throw new ServiceException(e.getMessage());
}
}
@Transactional(readOnly = true)
@Override
public T getById(int id) throws ServiceException {
try {
return dao.getById(id);
} catch (DaoException e) {
logger.debug(e);
throw new ServiceException(e.getMessage());
}
}
@Transactional(readOnly = true)
@Override
public List<T> getAll() throws ServiceException {
try {
return dao.getAll();
} catch (DaoException e) {
logger.debug(e);
throw new ServiceException(e.getMessage());
}
}
}
用户服务.java:
@Service
public class UserService extends GenericService<User> {
private static Logger logger = Logger.getLogger(UserService.class);
@Autowired
private UserDao userDao;
@Transactional
public String checkUser(String userLogin, String userPassword) throws ServiceException {
String namePage = "errorAuthorization";
List<User> userList;
try {
userList = userDao.getByLoginAndPassword(userLogin, userPassword);
} catch (DaoException e) {
logger.debug(e);
throw new ServiceException(e.getMessage());
}
if(userList.size() != 0) {
return UserRoleChecker.defineUserPage(userList.get(0));
}
return namePage;
}
public void addUser(String userLogin, String userPassword, String userMail) throws ServiceException{
Role role = new Role(0, RoleType.USER);
User user = new User(0, userLogin, userPassword, userMail, role);
add(user);
}
}
用户 Controller .java:
@Controller
public class UserController {
private static String className = UserController.class.getName();
@Autowired
private UserService userService;
@RequestMapping(value = "/check_user", method = RequestMethod.POST)
public ModelAndView authorizationUser(HttpServletRequest request, HttpServletResponse response) {
ModelAndView modelAndView = new ModelAndView();
String returnPage;
try {
returnPage = userService.checkUser(request.getParameter(RequestParameter.USER_LOGIN), request.getParameter(RequestParameter.USER_PASSWORD));
} catch (ServiceException e) {
returnPage = ErrorHandler.returnErrorPage(e.getMessage(), className);
}
modelAndView.setViewName(returnPage);
return modelAndView;
}
@RequestMapping(value = "/add_user", method = RequestMethod.POST)
public ModelAndView registrationUser(HttpServletRequest request, HttpServletResponse response) {
ModelAndView modelAndView = new ModelAndView();
String returnPage = Page.SUCCESSFUL_REGISTRATION;
try {
userService.addUser(request.getParameter(RequestParameter.USER_LOGIN), request.getParameter(RequestParameter.USER_PASSWORD), request.getParameter(RequestParameter.USER_MAIL));
} catch (ServiceException e) {
returnPage = ErrorHandler.returnErrorPage(e.getMessage(), className);
}
modelAndView.setViewName(returnPage);
return modelAndView;
}
}
根上下文.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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config />
<context:component-scan base-package="by.netcracker.artemyev" />
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/airline?useSSL=false" />
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="initialSize" value="5"/>
<property name="maxTotal" value="10"/>
</bean>
<bean id="entityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="by.netcracker.artemyev" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="database" value="MYSQL" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="debug">true</prop>
<prop key="connection.isolation">2</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManager" />
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
</beans>
日志:
org.springframework.web.context.ContextLoader 2017-05-09 11:48:21,198 ERROR - Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'userService' is expected to be of type 'by.netcracker.artemyev.service.UserService' but was actually of type 'com.sun.proxy.$Proxy31'
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4744)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5206)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1702)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:456)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:405)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1468)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1309)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1401)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:829)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:324)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'userService' is expected to be of type 'by.netcracker.artemyev.service.UserService' but was actually of type 'com.sun.proxy.$Proxy31'
at org.springframework.beans.factory.support.DefaultListableBeanFactory.checkBeanNotOfRequiredType(DefaultListableBeanFactory.java:1503)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1482)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 60 more
问题:请解释为什么我会遇到这个问题以及如何解决这个错误?
最佳答案
这个问题的原始问题是通过从 UserDao
中删除 @Transactional
解决的,这是需要完成的,因为 Service
实现负责用于事务管理,而不是 DAO。
还建议从 UserDao
构造函数中删除 @Autowired
,因为构造函数没有参数,即它没有 Autowiring 任何东西。
现在该问题已得到修复,代码在 UserController
的 userService
字段中也存在类似问题。
由于 Spring 使用代理模式,UserController
需要一个由 UserService
实现的接口(interface),而不是类本身。
通常的做法是将类重命名为 UserServiceImpl
,然后添加一个名为 UserService
的接口(interface)。继续让 UserController
类的字段 userService
为 UserService
类型。
关于java - 不满意的依赖异常 : Error creating bean(by BeanNotOfRequiredTypeException),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43858420/
reqwest v0.9 将 serde v1.0 作为依赖项,因此实现 converting serde_json errors into reqwest error . 在我的代码中,我使用 se
我有这个代码: let file = FileStorage { // ... }; file.write("Test", bytes.as_ref()) .map_err(|e| Mu
我只是尝试用angular-cli创建一个新项目,然后运行服务器,但是它停止并显示一条有趣的消息:Error: No errors。 我以这种方式更新了(希望有帮助):npm uninstall -g
我从我的 javascript 发送交易 Metamask 打开传输对话框 我确定 i get an error message in metamask (inpage.js:1 MetaMask -
这个问题在这里已经有了答案: How do you define custom `Error` types in Rust? (3 个答案) How to get a reference to a
我想知道两者之间有什么大的区别 if let error = error{} vs if error != nil?或者只是人们的不同之处,比如他们如何用代码表达自己? 例如,如果我使用这段代码: u
当我尝试发送超过 50KB 的图像时,我在 Blazor 服务器应用程序上收到以下错误消息 Error: Connection disconnected with error 'Error: Serv
我有一个error-page指令,它将所有异常重定向到错误显示页面 我的web.xml: [...] java.lang.Exception /vi
我有这样的对象: address: { "phone" : 888, "value" : 12 } 在 WHERE 中我需要通过 address.value 查找对象,但是在 SQL 中有函数
每次我尝试编译我的代码时,我都会遇到大量错误。这不是我的代码的问题,因为它在另一台计算机上工作得很好。我尝试重新安装和修复,但这没有帮助。这是整个错误消息: 1>------ Build starte
在我的代码的类部分,如果我写一个错误,则在不应该的情况下,将有几行报告为错误。我将'| error'放在可以从错误中恢复的良好/安全位置,但是我认为它没有使用它。也许它试图在某个地方恢复中间表情? 有
我遇到了 csv 输入文件整体读取故障的问题,我可以通过在 read_csv 函数中添加 "error_bad_lines=False" 来删除这些问题来解决这个问题。 但是我需要报告这些造成问题的文
在 Spring 中,验证后我们在 controller 中得到一个 BindingResult 对象。 很简单,如果我收到验证错误,我想重新显示我的表单,并在每个受影响的字段上方显示错误消息。 因此
我不知道出了什么问题,因为我用 Java 编程了大约一年,从来没有遇到过这个错误。在一分钟前在 Eclipse 中编译和运行工作,现在我得到这个错误: #A fatal error has been
SELECT to_char(messages. TIME, 'YYYY/MM/DD') AS FullDate, to_char(messages. TIME, 'MM/DD
我收到这些错误: AnonymousPath\Anonymized.vb : error BC30037: Character is not valid. AnonymousPath\Anonymiz
我刚刚安装了 gridengine 并在执行 qstat 时出现错误: error: commlib error: got select error (Connection refused) erro
嗨,我正在学习 PHP,我从 CRUD 系统开始,我在 Windows 上安装了 WAMP 服务器,当我运行它时,我收到以下错误消息。 SCREAM: Error suppression ignore
我刚刚开始一个新项目,我正在学习核心数据教程,可以找到:https://www.youtube.com/watch?v=zZJpsszfTHM 我似乎无法弄清楚为什么会抛出此错误。我有一个名为“Exp
当我使用 Jenkins 运行新构建时,出现以下错误: "FilePathY\XXX.cpp : fatal error C1853: 'FilePathZ\XXX.pch' precompiled
我是一名优秀的程序员,十分优秀!