Spring Autowired“不是托管类型”

时间:2017-08-19 16:34:35

标签: spring maven spring-mvc autowired

我对Spring有这个问题。我无法理解什么不去。 应该是autowired属性的问题,我还咨询了网站上的其他指南,但没有成功。

this is  structure

控制台错误

ago 19, 2017 6:25:12 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
AVVERTENZA: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Trenitalia2' did not find a matching property.
ago 19, 2017 6:25:12 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Server version:        Apache Tomcat/9.0.0.M22
ago 19, 2017 6:25:12 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Server built:          Jun 21 2017 09:44:18 UTC
ago 19, 2017 6:25:12 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Server number:         9.0.0.0
ago 19, 2017 6:25:12 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: OS Name:               Windows 10
ago 19, 2017 6:25:12 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: OS Version:            10.0
ago 19, 2017 6:25:12 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Architecture:          amd64
ago 19, 2017 6:25:12 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Java Home:             C:\Program Files\Java\jre1.8.0_131
ago 19, 2017 6:25:12 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: JVM Version:           1.8.0_131-b11
ago 19, 2017 6:25:12 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: JVM Vendor:            Oracle Corporation
ago 19, 2017 6:25:12 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: CATALINA_BASE:         C:\Users\Luca\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
ago 19, 2017 6:25:12 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: CATALINA_HOME:         C:\Program Files\Apache Software Foundation\Tomcat 9.0_Tomcat999
ago 19, 2017 6:25:12 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Command line argument: -Dcatalina.base=C:\Users\Luca\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
ago 19, 2017 6:25:12 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Command line argument: -Dcatalina.home=C:\Program Files\Apache Software Foundation\Tomcat 9.0_Tomcat999
ago 19, 2017 6:25:12 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Command line argument: -Dwtp.deploy=C:\Users\Luca\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
ago 19, 2017 6:25:12 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Command line argument: -Djava.endorsed.dirs=C:\Program Files\Apache Software Foundation\Tomcat 9.0_Tomcat999\endorsed
ago 19, 2017 6:25:12 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Command line argument: -Dfile.encoding=Cp1252
ago 19, 2017 6:25:12 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFORMAZIONI: 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_131\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre1.8.0_131/bin/server;C:/Program Files/Java/jre1.8.0_131/bin;C:/Program Files/Java/jre1.8.0_131/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Users\Luca\AppData\Local\Microsoft\WindowsApps;;C:\eclipse-jee-neon-3-win32-x86_64\eclipse;;.]
ago 19, 2017 6:25:12 PM org.apache.coyote.AbstractProtocol init
INFORMAZIONI: Initializing ProtocolHandler ["http-nio-8080"]
ago 19, 2017 6:25:13 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFORMAZIONI: Using a shared selector for servlet write/read
ago 19, 2017 6:25:13 PM org.apache.coyote.AbstractProtocol init
INFORMAZIONI: Initializing ProtocolHandler ["ajp-nio-8009"]
ago 19, 2017 6:25:13 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFORMAZIONI: Using a shared selector for servlet write/read
ago 19, 2017 6:25:13 PM org.apache.catalina.startup.Catalina load
INFORMAZIONI: Initialization processed in 428 ms
ago 19, 2017 6:25:13 PM org.apache.catalina.core.StandardService startInternal
INFORMAZIONI: Starting service [Catalina]
ago 19, 2017 6:25:13 PM org.apache.catalina.core.StandardEngine startInternal
INFORMAZIONI: Starting Servlet Engine: Apache Tomcat/9.0.0.M22
ago 19, 2017 6:25:14 PM org.apache.jasper.servlet.TldScanner scanJars
INFORMAZIONI: 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.
ago 19, 2017 6:25:14 PM org.apache.catalina.core.ApplicationContext log
INFORMAZIONI: No Spring WebApplicationInitializer types detected on classpath
ago 19, 2017 6:25:14 PM org.apache.catalina.core.ApplicationContext log
INFORMAZIONI: Initializing Spring root WebApplicationContext
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Sat Aug 19 18:25:14 CEST 2017]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/security.xml]
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'abilitazioneService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private it.uniroma3.repository.AbilitazioneRepository it.uniroma3.service.AbilitazioneService.abilitazioneRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'abilitazioneRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class it.uniroma3.model.Abilitazione

DBWEBCONFIG

@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan("it.uniroma3")
@PropertySource("classpath:application.properties")
@EnableJpaRepositories("it.uniroma3.repository")
public class DBWebConfig {

    private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
    private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
    private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
    private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
    private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL = "hibernate.hbm2ddl.auto";

    @Resource
    private Environment env;

    @Bean
    public DataSource dataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
        dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
        dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
        dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));

        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();

        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistence.class);
        entityManagerFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));

        entityManagerFactoryBean.setJpaProperties(hibProperties());






        return entityManagerFactoryBean;
    }

    private Properties hibProperties() {
        Properties properties = new Properties();
        properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
        properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
        properties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL));

        return properties;
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
        return transactionManager;
    }

    @Bean
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource source = new ResourceBundleMessageSource();
        source.setBasename(env.getRequiredProperty("message.source.basename"));
        source.setUseCodeAsDefaultMessage(true);
        return source;
    }

}

的applicationContext.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:jdbc="http://www.springframework.org/schema/jdbc"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:jpa="http://www.springframework.org/schema/data/jpa"
        xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.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-1.8.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

        <context:component-scan base-package="it.uniroma3">
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>


         <import resource="security.xml"/>

    </beans>

APPLICATION.PROPERTIES

message.source.basename=i18n/messages


db.driver=org.postgresql.Driver
db.url=jdbc:postgresql://localhost/trenitalia
db.username=postgres
db.password=postgres

hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
entitymanager.packages.to.scan=it.uniroma3.model 
hibernate.hbm2ddl.auto=create
it.uniroma3.model.Abilitazione , 

为了更好地理解我添加了模板,存储库和相关服务,我希望我能尽可能理解

package it.uniroma3.model;

import java.time.LocalDate;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.jboss.logging.Message;
import org.springframework.format.annotation.NumberFormat;

@Entity
public class Abilitazione {

    @Id
    @GeneratedValue
    private Long id;

    @Size(min=1, message="Non è un nome valido")
    private String nomeAbilitazione;
    @Size(min=3, message="Non è un link valido")
    private String linkAllegato;
    @Size(max=1, message="Non è uno stato valido")
    private String info;

    @NotNull
    @Min(1)
    @Max(31)
    private Integer giornoScadenza;

    @NotNull
    @Min(1)
    @Max(12)
    private Integer meseScadenza;

    @NotNull
    @Min(2000)
    @Max(2100)
    private Integer annoScadenza;

    @NotNull
    @Min(1)
    @Max(31)
    private Integer giornoConseguimento;

    @NotNull
    @Min(1)
    @Max(12)
    private Integer meseConseguimento;

    @NotNull
    @Min(2000)
    @Max(2100)
    private Integer annoConseguimento;

    private LocalDate dataLocale;
    private LocalDate dataScadenzaAbilitazioneTot;
    private LocalDate dataConseguimentoAbilitazioneTot;



    @ManyToOne
    private Dipendente dipendente;

    public Long getId() {
        return id;
    }

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

    public String getNomeAbilitazione() {
        return nomeAbilitazione;
    }

    public void setNomeAbilitazione(String nomeAbilitazione) {
        this.nomeAbilitazione = nomeAbilitazione;
    }

    public String getLinkAllegato() {
        return linkAllegato;
    }

    public void setLinkAllegato(String linkAllegato) {
        this.linkAllegato = linkAllegato;
    }

    public Dipendente getDipendente() {
        return dipendente;
    }

    public void setDipendente(Dipendente dipendente) {
        this.dipendente = dipendente;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    public String getInfo() {
        return info;
    }

    public LocalDate getDataLocale() {
        this.dataLocale = LocalDate.now();
        return dataLocale;
    }

    public void setDataLocale(LocalDate dataLocale) {
        this.dataLocale = dataLocale;
    }

    public Integer getGiornoScadenza() {
        return giornoScadenza;
    }

    public void setGiornoScadenza(Integer giornoScadenza) {
        this.giornoScadenza = giornoScadenza;
    }

    public Integer getMeseScadenza() {
        return meseScadenza;
    }

    public Integer getAnnoConseguimento() {
        return annoConseguimento;
    }

    public Integer getGiornoConseguimento() {
        return giornoConseguimento;
    }

    public Integer getMeseConseguimento() {
        return meseConseguimento;
    }

    public void setAnnoConseguimento(Integer annoConseguimento) {
        this.annoConseguimento = annoConseguimento;
    }

    public void setGiornoConseguimento(Integer giornoConseguimento) {
        this.giornoConseguimento = giornoConseguimento;
    }

    public void setMeseConseguimento(Integer meseConseguimento) {
        this.meseConseguimento = meseConseguimento;
    }

    public void setMeseScadenza(Integer meseScadenza) {
        this.meseScadenza = meseScadenza;
    }

    public Integer getAnnoScadenza() {
        return annoScadenza;
    }

    public void setAnnoScadenza(Integer annoScadenza) {
        this.annoScadenza = annoScadenza;
    }

    public LocalDate getDataConseguimentoAbilitazioneTot() {
        return dataConseguimentoAbilitazioneTot;
    }

    public void setDataConseguimentoAbilitazioneTot(LocalDate dataConseguimentoAbilitazioneTot) {
        this.dataConseguimentoAbilitazioneTot = dataConseguimentoAbilitazioneTot;
    }

    public LocalDate getDataScadenzaAbilitazioneTot() {
        return dataScadenzaAbilitazioneTot;
    }

    public void setDataScadenzaAbilitazioneTot(LocalDate dataScadenzaAbilitazioneTot) {
        this.dataScadenzaAbilitazioneTot = dataScadenzaAbilitazioneTot;
    }
}

为了更好地理解我添加了模板,存储库和相关服务,我希望我能尽可能地理解。 AbilitazioneRepository

public interface AbilitazioneRepository extends JpaRepository<Abilitazione, Long>{

    List<Abilitazione> findByDipendente(Dipendente dipendente);

}

为了更好地理解我添加了模板,存储库和相关服务,我希望我能尽可能地理解。

AbilitazioneService

@Service
@Transactional
public class AbilitazioneService {

    @Autowired
    private AbilitazioneRepository abilitazioneRepository;

    public List<Abilitazione> findAll(){
        return abilitazioneRepository.findAll();
    }

    public void save(Abilitazione abilitazione){
        abilitazioneRepository.save(abilitazione);
    }

    public List<Abilitazione> findAllAbilitazioniDi(Dipendente dipendente){
        return abilitazioneRepository.findByDipendente(dipendente);
    }
    //aggiunta ora
    public Abilitazione findAbilitazioneConId(Long id){
        return abilitazioneRepository.findOne(id);
    }
    //aggiunta ora per la cancellazione
    public void delete(Long id){
        abilitazioneRepository.delete(id);
    }

}

IT.UNIROMA3.MODEL.DIPENDENTE CLASS

    @Entity
public class Dipendente {

    @Id
    @GeneratedValue
    private Long id;

    @Size(min=3,message="Inserisci un nome valido")
    private String nome;

    @Size(min=1,message="!")
    private String cognome;

    @NumberFormat
    private Integer cid;

    @Size(min=3,message="Inserisci un impianto valido")
    private String impianto;



    @OneToMany(mappedBy="dipendente", cascade = CascadeType.REMOVE)
    private List<Abilitazione> abilitazioni; 


    // plus getter and setter

1 个答案:

答案 0 :(得分:0)

你遗失了几件事:

1.将@Entity和@Table添加到实体(共享的项目中缺少):

@Entity
@Table
public class Abilitazione 



@Entity
@Table
public class Dipendente

2.更换存储库定义,如下所示:

public interface AbilitazioneRepository extends JpaRepository<Abilitazione, Long>{

 Dipendente findByDipendenteId(Long dipendenteId);
}
  1. pom.xml中spring数据和hibernate依赖项之间存在很多依赖冲突。