[java] Autowiring fails: Not an managed Type

I have a big problem in my diploma project and would be very glad if you guys could help me! I made a Maven Multi Module Project and have 3 "Core-projects"

  • NaviClean: (Parent)
  • NaviCleanDomain: contains the domain model with all my entities and an interface MeinRemoteDienst which is needed by NaviCleanServer and NaviCleanCleint for the Hessianprotocol
  • NaviCleanClient: conatins the GUI and a Hessian connection to NaviCleanServer
  • NaviCleanServer: Here are my repositories, my connection to the DB and the Implementation of the interface einRemoteDienst NaviCleanServer & NaviCleanClient have NaviCleanDomain in Maven as Dependency.

Now every time I try to start the Server on my Tomcat I get the following error:

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

ModelBase:

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;
    }

}

Kassa:

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);
}

BaseRepository

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

}

KassaRepository:

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);
    }

}

application-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: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>

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

root-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"
    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>

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

Here is what I already tried: 1. I wrote this test which "went red":

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())));
    }

}

ERRORS:

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. I insertet in my persitence.xml my domainmodel an repositories manually. The result was a "green" test but I wasn't still able to start the server...

Thanks alot in advance!!! I can't imagine what it would be without you :)

This question is related to java spring spring-mvc spring-data-jpa hessian

The answer is


In spring boot I get same exception by using CrudRepository because I forgot to set generic types. I want to write it here in case it helps someone.

errorneous definition:

public interface OctopusPropertiesRepository extends CrudRepository

error:

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

successfull definition:

public interface OctopusPropertiesRepository extends CrudRepository<OctopusProperties,Long>{

You should extend the scope of the component-scan e.g. <context:component-scan base-package="at.naviclean" /> since you placed the entities in package at.naviclean.domain;

This should help you to get rid the exeption: Not an managed type: class at.naviclean.domain.Kassa

For further debugging you could try to dump the application context (see javadoc) to explore which classes have been detected by the component-scan if some are still no recognized check their annotation (@Service, @Component etc.)

EDIT:

You also need to add the classes to your persistence.xml

<persistence-unit>
    <class>at.naviclean.domain.Kassa</class>
     ...
</persistence-unit>

Just in case some other poor sod ends up here because they are having the same issue I was: if you have multiple data sources and this is happening with the non-primary data source, then the problem might be with that config. The data source, entity manager factory, and transaction factory all need to be correctly configured, but also -- and this is what tripped me up -- MAKE SURE TO TIE THEM ALL TOGETHER! @EnableJpaRepositories (configuration class annotation) must include entityManagerFactoryRef and transactionManagerRef to pick up all the configuration!

The example in this blog finally helped me see what I was missing, which (for quick reference) were the refs here:

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

Hope this helps save someone else from the struggle I've endured!


For me the error was quite simple based on what @alfred_m said..... tomcat had 2 jars conflicting having same set of Class names and configuration.

What happened was ..............I copied my existing project to make a new project out of the existing project. but without making required changes, I started working on other project. Henec 2 projects had same classes and configuration files, resulting into conflict.

Deleted the copied project and things started working!!!!


you need check 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
 .....

If anyone is strugling with the same problem I solved it by adding @EntityScan in my main class. Just add your model package to the basePackages property.


After encountering this issue and tried different method of adding the entity packaname name to EntityScan, ComponentScan etc, none of it worked.

Added the package to packageScan config in the EntityManagerFactory of the repository config. The below code gives the code based configuration as opposed to XML based ones answered above.

@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();
}

When you extend indirectly JpaRepository ( KassaRepository extends BaseRepository that extends JpaRepository) then you have to annotate BaseRepository with @NoRepositoryBean :

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

You get the same exception when you pass the incorrect Entity object to the CrudRepository in the repository class.

public interface XYZRepository extends CrudRepository<IncorrectEntityClass, Long>

Refering to Oliver Gierke's hint:

When the manipulation of the persistance.xml does the trick, then you created a normal java-class instead of a entity-class.

When creating a new entity-class then the entry in the persistance.xml should be set by Netbeans (in my case).

But as mentioned by Oliver Gierke you can add the entry later to the persistance.xml (if you created a normal java-class).


In my case, when using IntelliJ, I had multiple modules in the project. The main module was dependent on another module which had the maven dependencies on Spring.

The main module had Entitys and so did the second module. But when I ran the main module, only the Entitys from the second module got recognized as managed classes.

I then added Spring dependencies on the main module as well, and guess what? It recognized all the Entitys.


For Controllers, @SpringBootApplication(scanBasePackages = {"com.school.controllers"})

For Respositories, @EnableJpaRepositories(basePackages = {"com.school.repos"})

For Entities, @EntityScan(basePackages = {"com.school.models"})

This will slove

"Can't Autowire @Repository annotated interface"

problem as well as

Not an managed Type

problem. Sample configuration below

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);
    }

}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to spring-mvc

Two Page Login with Spring Security 3.2.x ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized The type WebMvcConfigurerAdapter is deprecated RestClientException: Could not extract response. no suitable HttpMessageConverter found Spring boot: Unable to start embedded Tomcat servlet container UnsatisfiedDependencyException: Error creating bean with name 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

Examples related to spring-data-jpa

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? No converter found capable of converting from type to type Consider defining a bean of type 'service' in your configuration [Spring boot] Check date between two other dates spring data jpa How to beautifully update a JPA entity in Spring Data? Spring Data and Native Query with pagination Disable all Database related auto configuration in Spring Boot crudrepository findBy method signature with multiple in operators? How does the FetchMode work in Spring Data JPA

Examples related to hessian

Autowiring fails: Not an managed Type