创建名称为“ CommunityService”的bean时出错

时间:2018-11-26 07:56:57

标签: java spring jpa

我在示例项目中使用spring数据jpa,我配置了spring数据jpa,如下面的代码所示。当我运行项目时,出现以下错误,我用谷歌搜索了很多,但是没有找到合适的解决方案,因此对此提供了任何帮助。

  

严重:StandardWrapper.Throwable       org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“ CommunityService”的bean时出错:通过字段“ userRepository”表示的不满意的依赖关系;
  [...]
  由以下原因引起:org.springframework.beans.factory.BeanCreationException:创建名称为'UserRepository'的bean时出错:调用init方法失败;嵌套异常是java.lang.IllegalArgumentException:不是托管类型:类core.entities.User

完整堆栈跟踪

Nov 25, 2018 11:10:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         C:\D\java projects eclipse\spring core\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Nov 25, 2018 11:10:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         C:\Program Files\Apache Software Foundation\Tomcat 7.0
Nov 25, 2018 11:10:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\D\java projects eclipse\spring core\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Nov 25, 2018 11:10:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Program Files\Apache Software Foundation\Tomcat 7.0
Nov 25, 2018 11:10:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\D\java projects eclipse\spring core\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
Nov 25, 2018 11:10:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Program Files\Apache Software Foundation\Tomcat 7.0\endorsed
Nov 25, 2018 11:10:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Nov 25, 2018 11:10:36 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre1.8.0_121\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_121/bin/server;C:/Program Files/Java/jre1.8.0_121/bin;C:/Program Files/Java/jre1.8.0_121/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Program Files\Java\jdk1.8.0_121\bin;C:\Program Files\MySQL\MySQL Utilities 1.6\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\;C:\WINDOWS\system32\config\systemprofile\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\apache-maven-3.5.0\bin;C:\Program Files\Git\cmd;C:\Program Files (x86)\Skype\Phone\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\Microsoft\Web Platform Installer\;C:\setups\wildfly-12.0.0.Final\bin;C:\WINDOWS\System32\OpenSSH\;C:\Windows\System32;C:\Users\lilly\AppData\Local\Microsoft\WindowsApps;C:\setups\spring-2.0.1.RELEASE\bin;;C:\E\eclipse;;.
Nov 25, 2018 11:10:36 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Nov 25, 2018 11:10:36 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Nov 25, 2018 11:10:36 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1252 ms
Nov 25, 2018 11:10:36 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Nov 25, 2018 11:10:36 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.78
Nov 25, 2018 11:10:40 PM org.apache.catalina.startup.TldConfig execute
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Nov 25, 2018 11:10:40 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Nov 25, 2018 11:10:41 PM org.apache.catalina.util.SessionIdGeneratorBase createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [423] milliseconds.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Nov 25, 2018 11:10:41 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring DispatcherServlet 'dispatcherServlet'
Nov 25, 2018 11:10:43 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
Nov 25, 2018 11:10:43 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.0.CR1}
Nov 25, 2018 11:10:43 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Nov 25, 2018 11:10:43 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
Nov 25, 2018 11:10:44 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Nov 25, 2018 11:10:45 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Nov 25, 2018 11:10:45 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'CommunityService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class core.entities.User
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:696)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:662)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:710)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:587)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:526)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:169)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1269)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1182)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5368)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1571)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1561)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class core.entities.User
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1745)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273)  

web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">

    <display-name>spring_core-29</display-name>

   <!--
        - Location of the XML file that defines the root application context.
        - Applied by ContextLoaderListener.
    -->
  <!--context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/mvc-config.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener> 
  <   <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>  -->


    <!--
        - Servlet that dispatches request to registered handlers (Controller implementations).
    -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/ui/*</url-pattern>
    </servlet-mapping>

</web-app>  

mvc-config.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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:repository="http://www.springframework.org/schema/data/repository"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository.xsd">

    <context:annotation-config />
    <context:component-scan base-package="core" />
    <context:component-scan base-package="springmodule" />
    <bean id="ViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <mvc:annotation-driven />
    <jpa:repositories base-package="core.daos"  entity-manager-factory-ref="entitiyManagerFactory"/>

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/jpa_db" />
        <property name="username" value="root" />
        <property name="password" value="tiger" />
    </bean>
    <bean id="entitiyManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <!-- <property name="persistenceUnitName" value="jpaData"/> -->
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="core.entities.*" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entitiyManagerFactory"></property>
    </bean>

</beans>  

core.entities.User.java

package core.entities;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="user")
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private String id;
    private String name;
    private String username;
    private String password;
    public User(){}
    public User(String id, String name, String username, String password) {
        super();
        this.id = id;
        this.name = name;
        this.username = username;
        this.password = password;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }


}  

存储库

package core.daos;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import core.entities.User;
@Repository("UserRepository")
public interface UserRepository extends CrudRepository<User, String>{

}  

CommunityService

package core.services;
import core.entities.User;
import core.enums.Role;

public interface CommunityService  {
    core.entities.User findByUserName(String userName);
    User createUser(User user, Role role);
    User createUser(User user);
    Iterable<User> findAll();
}  

CommunityServiceImpl

package core.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import core.daos.UserRepository;
import core.entities.User;
import core.enums.Role;

@Service("CommunityService")
@Transactional(propagation=Propagation.REQUIRED)
public class CommunityServiceImpl implements CommunityService {
    @Autowired
    private UserRepository userRepository;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        return null;
    }

    public User createUser(User user) {
        // TODO Auto-generated method stub
        return userRepository.save(user);
    }

    public User findByUserName(String userName) {
        // TODO Auto-generated method stub
        return null;
    }

    public User createUser(User user, Role role) {
        // TODO Auto-generated method stub
        return null;
    }

    public Iterable<User> findAll() {
    return userRepository.findAll();
    }
}  

控制器

package springmodule.controller;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import core.entities.User;
import core.services.CommunityService;

@Controller
public class UserController {
    @Autowired
    private CommunityService communityService;
    @RequestMapping(value="/user",method=RequestMethod.POST)
    public User home(@ModelAttribute User user){
        return communityService.createUser(user);
    }
    @RequestMapping(value="/index",method=RequestMethod.GET)
    public String index(ModelMap modelMap){
         modelMap.put("user",communityService.findAll());
         return "welcome";
    }

}

2 个答案:

答案 0 :(得分:1)

您的控制器具有不同的程序包命名约定,而服务层具有不同的命名约定。 指定每个要扫描的软件包。

 <context:component-scan base-package="springmodule.controller, core.services, core.entities, core.enums, core.daos" />

尽管这也应该起作用。

<context:component-scan base-package="springmodule.controller, core" />

答案 1 :(得分:0)

您有

的副本
<context:component-scan base-package="core" />
<context:component-scan base-package="springmodule" />

似乎springmodule是最重要的核心,请删除:

<context:component-scan base-package="springmodule" />

也尝试使用:

packagesToScan="com.entities"