45

我的文凭项目有一个大问题,如果你们能帮助我,我会很高兴!我做了一个 Maven 多模块项目并有 3 个“核心项目”

  • NaviClean: (家长)
  • NaviCleanDomain:包含域模型以及我的所有实体和一个接口,该接口MeinRemoteDienst需要NaviCleanServerNaviCleanCleint用于Hessianprotocol
  • NaviCleanClient: 包含 GUI 和 Hessian 连接 NaviCleanServer
  • NaviCleanServer:这是我的存储库,我与数据库的连接以及接口的实现,einRemoteDienst NaviCleanServerNaviCleanClientNaviCleanDomainMaven 中作为依赖项。

现在每次我尝试在我的 Tomcat 上启动服务器时,我都会收到以下错误:

ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'transaktionsRepository': 
Injection of persistence dependencies failed; 
nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: 
Error loading class [at.naviclean.service.impl.MeinRemoteDienstImpl] for bean with name 'meinRemoteDienstImpl' defined in file [C:\Users\Fredy\Documents\workspace-sts-3.1.0.RELEASE\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\NaviCleanServer\WEB-INF\classes\at\naviclean\service\impl\MeinRemoteDienstImpl.class]: 
problem with class file or dependent class; 
nested exception is java.lang.NoClassDefFoundError: at/naviclean/service/MeinRemoteDienst
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:342)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    ……………….

模型库:

package at.naviclean.domain;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;

@SuppressWarnings("serial")
@MappedSuperclass
public class ModelBase implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @Version
    @Column(name = "ts")
    private Date timestamp;

    public Long getId() {
        return id;
    }

    public Date getTimestamp() {
        return timestamp;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }

}

卡萨:

package at.naviclean.domain;

import javax.persistence.Column;
import javax.persistence.Entity;

@SuppressWarnings("serial")
@Entity
public class Kassa extends ModelBase {

    @Column(name = "name", unique = true)
    private String name;

    @Column(name = "geld")
    private int geld;

    public Kassa(String name, int geld) {
        this.name = name;
        this.geld = geld;
    }

    public Kassa() {
    }

    public String getName() {
        return name;
    }

    public int getGeld() {
        return geld;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setGeld(int geld) {
        this.geld = geld;
    }

}

MeinRemoteDienst:

package at.naviclean.service;

import at.naviclean.domain.Kassa;

public interface MeinRemoteDienst {

    int getKassaCount(int plus);

    String getNameFromKassa(int id);

    Kassa findById(int id);
}

基础存储库

package at.naviclean.repositories;

import org.springframework.data.jpa.repository.JpaRepository;

import at.naviclean.domain.ModelBase;

public interface BaseRepository<T extends ModelBase> extends
        JpaRepository<T, Long> {
    T findById(long id);

}

卡萨存储库:

package at.naviclean.repositories;

import java.util.List;

import org.springframework.data.jpa.repository.Query;

import at.naviclean.domain.Kassa;

public interface KassaRepository extends BaseRepository<Kassa> {
    List<Kassa> findByGeld(int geld);

    Kassa findByName(String name);

    @Query("select k from Kassa k where k.geld = ?1")
    Kassa findByGeld1(int geld);
}

MeinRemoteDienstImpl:

package at.naviclean.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import at.naviclean.domain.Kassa;
import at.naviclean.repositories.KassaRepository;
import at.naviclean.service.MeinRemoteDienst;

@Service
public class MeinRemoteDienstImpl implements MeinRemoteDienst {

    @Autowired(required = true)
    public KassaRepository kassaR;

    public int getKassaCount(int plus) {
        return 2;
    }


    public String getNameFromKassa(int id) {
        return kassaR.findById(id + 0l).getName();
    }

    @Override
    public Kassa findById(int id) {
        return = kassaR.findById(id + 0l);
    }

}

应用程序上下文.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:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:repository="http://www.springframework.org/schema/data/repository"
    xsi:schemaLocation="http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


    <import resource="infrastructures.xml" />

    <jpa:repositories base-package="at.naviclean.repositories">
        <repository:exclude-filter type="regex"
            expression="at.naviclean.repositories.BaseRepository" />
    </jpa:repositories>

    <context:component-scan base-package="at.naviclean.service.impl" />

</beans>

基础设施.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:jdbc="http://www.springframework.org/schema/jdbc"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
                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">



        <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 name="showSql" value="true" />
                                <property name="generateDdl" value="true" />
                                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
                        </bean>
                </property>
        </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/kassatest" />
                <property name="username" value="root" />
                <property name="password" value="" />
        </bean>

        <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
                <property name="entityManagerFactory" ref="entityManagerFactory" />
        </bean>


        <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

</beans>

servlet-context.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:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:c="http://www.springframework.org/schema/c"
    xsi:schemaLocation="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/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">



<import resource="../root-context.xml" />
    <bean id="idMeinRemoteDienst" class="at.naviclean.service.impl.MeinRemoteDienstImpl" />
    <bean name="/MeinRemoteDienstHessian"
        class="org.springframework.remoting.caucho.HessianServiceExporter"
        p:serviceInterface="at.naviclean.service.MeinRemoteDienst"
        p:service-ref="idMeinRemoteDienst" />

</beans>

根上下文.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="classpath:META-INF/spring/application-context.xml" />

</beans>

网页.xml:

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

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


    <servlet>
        <servlet-name>/MeinRemoteDienstHessian</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>/MeinRemoteDienstHessian</servlet-name>
        <url-pattern>/remoting/*</url-pattern>
    </servlet-mapping>

</web-app>

这是我已经尝试过的: 1. 我写了这个“变红”的测试:

package at.spengergasse.kassa;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import at.naviclean.domain.Kassa;
import at.naviclean.repositories.KassaRepository;

@ContextConfiguration("classpath:META-INF/spring/application-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class KassaTest {

    @Autowired(required = true)
    private KassaRepository kassaR;

    @Before
    public void setUp() throws Exception {

    }

    @Test
    public void findByIdTest() {
        Kassa k = kassaR.findById(2);

        assertThat(k, is(not(nullValue())));
    }

    @Test
    public void findByGeld() {
        Kassa k = kassaR.findByGeld1(1200);

        assertThat(k, is(not(nullValue())));
    }

    @Test
    public void test() {
        Kassa vorher = new Kassa("ssf", 222);
        kassaR.save(vorher);
        Kassa nachher = kassaR.findById(vorher.getId());
        kassaR.delete(nachher);
        assertThat(vorher.getId(), is(equalTo(nachher.getId())));
    }

}

错误:

ERROR: org.springframework.test.context.TestContextManager - 
Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@41e22632] to prepare test instance [at.spengergasse.kassa.KassaTest@6639be68]
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:157)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)


Caused by: org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'meinRemoteDienstImpl': 
**Injection of autowired dependencies failed**; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: public at.naviclean.repositories.KassaRepository at.naviclean.service.impl.MeinRemoteDienstImpl.kassaR; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'kassaRepository': FactoryBean threw exception on object creation; 
nested exception is java.lang.IllegalArgumentException: **Not an managed type: class at.naviclean.domain.Kassa**
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
    ………..

2. 我在我的 persitence.xml 我的 domainmodel 中手动插入一个存储库。结果是“绿色”测试,但我仍然无法启动服务器......

非常感谢提前!!!我无法想象没有你会怎样:)

4

13 回答 13

133

我从Oliver Gierke 那里得到了一个非常有用的建议:

您得到的最后一个异常实际上表明您的 JPA 设置存在问题。“不是托管 bean”意味着不是 JPA 提供者知道的类型。如果您正在设置基于 Spring 的 JPA 应用程序,我建议您在已配置到包含 JPA 实体的包的 LocalContainerEntityManagerFactory 上配置“packagesToScan”属性。或者,您可以在 persistence.xml 中列出所有实体类,但这通常比较麻烦。

您收到的前一个错误(NoClassDefFound)表明提到的类在项目类路径中不可用。所以你可能想检查你拥有的模块间依赖关系。由于这两个相关的类似乎位于同一个模块中,因此它也可能只是对 Tomcat 的不完整部署的问题(WTP 有时有点讨厌)。我绝对建议您进行验证测试(就像您已经做过的那样)。由于这似乎导致您遇到不同的异常,我想这确实是一些 Eclipse 故障

谢谢!

于 2012-12-30T13:59:42.060 回答
10

您应该扩展组件扫描的范围,例如<context:component-scan base-package="at.naviclean" />,因为您将实体放在包中at.naviclean.domain;

这应该可以帮助您摆脱 exeption: Not an managed type: class at.naviclean.domain.Kassa

为了进一步调试,您可以尝试转储应用程序上下文(请参阅 javadoc)以探索组件扫描已检测到哪些类,如果仍然无法识别某些类,请检查它们的注释(@Service、@Component 等)

编辑:

您还需要将类添加到您的persistence.xml

<persistence-unit>
    <class>at.naviclean.domain.Kassa</class>
     ...
</persistence-unit>
于 2012-12-28T12:43:15.547 回答
9

如果有人遇到同样的问题,我通过添加@EntityScan我的主类来解决它。只需将模型包添加到 basePackages 属性即可。

于 2018-07-27T01:47:07.327 回答
6

在春季启动中,我使用 CrudRepository 得到了同样的异常,因为我忘记设置泛型类型。我想把它写在这里以防它对某人有帮助。

错误定义:

public interface OctopusPropertiesRepository extends CrudRepository

错误:

Caused by: java.lang.IllegalArgumentException: Not a managed type: class java.lang.Object

成功定义:

public interface OctopusPropertiesRepository extends CrudRepository<OctopusProperties,Long>{
于 2016-08-08T07:19:13.090 回答
4

对于控制器,@SpringBootApplication(scanBasePackages = {"com.school.controllers"})

对于存储库,@EnableJpaRepositories(basePackages = {"com.school.repos"})

对于实体,@EntityScan(basePackages = {"com.school.models"})

这会喜欢

“无法自动装配 @Repository 注释接口”

问题以及

不是托管类型

问题。下面的示例配置

package com.school.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;


@SpringBootApplication(scanBasePackages = {"com.school.controllers"})
@EnableJpaRepositories(basePackages = {"com.school.repos"})
@EntityScan(basePackages = {"com.school.models"})
public class SchoolApplication {

    public static void main(String[] args) {
        SpringApplication.run(SchoolApplication.class, args);
    }

}
于 2020-06-07T07:15:58.517 回答
3

就我而言,当使用 IntelliJ 时,我在项目中有多个模块。主模块依赖于另一个对 Spring 具有 Maven 依赖关系的模块。

主模块有Entitys,第二个模块也有。但是当我运行主模块时,只有Entity第二个模块中的 s 被识别为托管类。

然后我也在主模块上添加了 Spring 依赖项,你猜怎么着?它识别了所有的Entitys。

于 2015-11-09T11:45:57.297 回答
3

遇到此问题并尝试将实体包名称名称添加到 EntityScan、ComponentScan 等的不同方法后,均无济于事。

将包添加到存储库配置的 EntityManagerFactory 中的 packageScan 配置。下面的代码给出了基于代码的配置,而不是上面回答的基于 XML 的配置。

@Primary
@Bean(name = "entityManagerFactory")
public EntityManagerFactory entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setDataSource(dataSource);
    emf.setJpaVendorAdapter(jpaVendorAdapter);
    emf.setPackagesToScan("org.package.entity");
    emf.setPersistenceUnitName("default"); 
    emf.afterPropertiesSet();
    return emf.getObject();
}
于 2018-08-10T14:37:51.107 回答
2

你需要检查 packagesToScan。

<bean id="entityManagerFactoryDB" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    <property name="dataSource" ref="dataSourceDB" />
    <property name="persistenceUnitName" value="persistenceUnitDB" />
    <property name="packagesToScan" value="at.naviclean.domain" />
                                            //here
 .....
于 2016-08-08T15:44:08.987 回答
1

当您间接扩展 JpaRepository(KassaRepository 扩展了扩展 JpaRepository 的 BaseRepository)时,您必须使用以下命令注释 BaseRepository @NoRepositoryBean

@NoRepositoryBean
public interface BaseRepository<T extends ModelBase> extends JpaRepository<T, Long> {
    T findById(long id);
}
于 2017-11-28T11:10:30.053 回答
1

以防万一其他一些糟糕的草皮最终出现在这里,因为他们遇到了与我相同的问题:如果您有多个数据源并且这种情况发生在非主数据源上,那么问题可能出在该配置上。数据源、实体管理器工厂和事务工厂都需要正确配置,而且——这就是让我感到困惑的地方——确保将它们全部捆绑在一起!@EnableJpaRepositories(配置类注解)必须包含entityManagerFactoryReftransactionManagerRef提取所有配置!

这个博客中的示例最终帮助我了解了我所缺少的内容,其中(供快速参考)是这里的参考:

@EnableJpaRepositories(
    entityManagerFactoryRef = "barEntityManagerFactory",
    transactionManagerRef = "barTransactionManager",
    basePackages = "com.foobar.bar")

希望这有助于将其他人从我所忍受的斗争中拯救出来!

于 2020-01-25T04:31:29.143 回答
0

参考 Oliver Gierke 的提示:

当persistance.xml 的操作成功时,您创建了一个普通的java 类而不是实体类。

当创建一个新的实体类时,persistance.xml 中的条目应该由 Netbeans 设置(在我的例子中)。

但正如 Oliver Gierke 所提到的,您可以稍后将该条目添加到 persistence.xml(如果您创建了一个普通的 java 类)。

于 2013-11-12T21:53:13.260 回答
0

对我来说,基于@alfred_m 所说的错误非常简单...... tomcat 有 2 个 jars 冲突,它们具有相同的类名和配置集。

发生的事情是......我复制了我现有的项目以从现有项目中创建一个新项目。但没有进行必要的更改,我开始从事其他项目。Henec 2 项目有相同的类和配置文件,导致冲突。

删除了复制的项目,事情开始了!!!!

于 2018-04-25T12:14:24.787 回答
0

当您将不正确的 Entity 对象传递给存储库类中的 CrudRepository 时,您会得到相同的异常。

public interface XYZRepository extends CrudRepository<IncorrectEntityClass, Long>
于 2019-09-03T10:46:17.043 回答