Error creating bean with name 'topicosController' defined in file
Error creating bean with name 'topicosController' defined in file
Oi João,
Posta aqui o erro completo que saiu no console pra gente entender melhor qual o problema.
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2022-04-07 09:04:13.173 ERROR 13168 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'topicosController': Unsatisfied dependency expressed through field 'topicoRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'topicoRepository' defined in br.com.alura.forum.repository.TopicoRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class br.com.alura.forum.modelo.Topico at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:659) ~[spring-beans-5.3.18.jar:5.3.18] AutowiredAnnotationBeanPostProcessor.java:659 at at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:740) ~[spring-boot-2.6.6.jar:2.6.6] SpringApplication.java:740 at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415) ~[spring-boot-2.6.6.jar:2.6.6] SpringApplication.java:415 at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) ~[spring-boot-2.6.6.jar:2.6.6] SpringApplication.java:303 at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312) ~[spring-boot-2.6.6.jar:2.6.6] SpringApplication.java:1312 at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.6.jar:2.6.6] SpringApplication.java:1301 at br.com.alura.forum.ForumApplication.main(ForumApplication.java:10) ~[classes/:na] ForumApplication.java:10 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:na] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Unknown Source) ~[na:na] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.6.6.jar:2.6.6] RestartLauncher.java:49 Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'topicoRepository' defined in br.com.alura.forum.repository.TopicoRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class br.com.alura.forum.modelo.Topico at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.18.jar:5.3.18] AbstractAutowireCapableBeanFactory.java:1804
DefaultListableBeanFactory.java:1389 at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309) ~[spring-beans-5.3.18.jar:5.3.18] DefaultListableBeanFactory.java:1309 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:656) ~[spring-beans-5.3.18.jar:5.3.18] AutowiredAnnotationBeanPostProcessor.java:656 ... 25 common frames omitted Caused by: java.lang.IllegalArgumentException: Not a managed type: class br.com.alura.forum.modelo.Topico at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:582) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final] MetamodelImpl.java:582 at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:85) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final] MetamodelImpl.java:85 at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.(JpaMetamodelEntityInformation.java:75) ~[spring-data-jpa-2.6.3.jar:2.6.3] JpaMetamodelEntityInformation.java:75 at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:66) ~[spring-data-jpa-2.6.3.jar:2.6.3] org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.18.jar:5.3.18] AbstractAutowireCapableBeanFactory.java:1863 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.18.jar:5.3.18] AbstractAutowireCapableBeanFactory.java:1800 ... 35 common frames omitted
O erro: java.lang.IllegalArgumentException: Not a managed type: class br.com.alura.forum.modelo.Topico
Verifica se a classe Topico está com a anotação da JPA @Entity
e verifica também o pacote da classe main(ForumApplication
)
Esta com esse erro agora
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2022-04-07 11:44:24.528 ERROR 5820 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: br.com.alura.forum.ForumApplication at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.18.jar:5.3.18] AbstractAutowireCapableBeanFactory.java:1804 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.18.jar:5.3.18] AbstractAutowireCapableBeanFactory.java:620 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.18.jar:5.3.18] AbstractAutowireCapableBeanFactory.java:542 at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.18.jar:5.3.18] AbstractBeanFactory.java:335 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.18.jar:5.3.18] DefaultSingletonBeanRegistry.java:234 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.18.jar:5.3.18] AbstractBeanFactory.java:333 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.18.jar:5.3.18] AbstractBeanFactory.java:208 at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.18.jar:5.3.18] AbstractApplicationContext.java:1154 at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.18.jar:5.3.18] AbstractApplicationContext.java:908 at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.18.jar:5.3.18] AbstractApplicationContext.java:583 at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.6.jar:2.6.6] ServletWebServerApplicationContext.java:145 at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:740) ~[spring-boot-2.6.6.jar:2.6.6] SpringApplication.java:740 at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415) ~[spring-boot-2.6.6.jar:2.6.6] SpringApplication.java:415 at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) ~[spring-boot-2.6.6.jar:2.6.6] SpringApplication.java:303 at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312) ~[spring-boot-2.6.6.jar:2.6.6] SpringApplication.java:1312 at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.6.jar:2.6.6] SpringApplication.java:1301 at br.com.alura.forum.ForumApplication.main(ForumApplication.java:13) ~[classes/:na] ForumApplication.java:13 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:na] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Unknown Source) ~[na:na]
Caused by: org.hibernate.AnnotationException: No identifier specified for entity: br.com.alura.forum.ForumApplication at org.hibernate.cfg.InheritanceState.determineDefaultAccessType(InheritanceState.java:266) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final] InheritanceState.java:266 at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:211) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final] InheritanceState.java:211 at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:772) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final] AnnotationBinder.java:772 at ] MetadataBuildingProcess.java:282 org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.18.jar:5.3.18] LocalContainerEntityManagerFactoryBean.java:365
AbstractAutowireCapableBeanFactory.java:1800 ... 21 common frames omitted
Oi João,
Parece que você colocou a anotação @Entity
na classe ForumApplication
. Mas essa anotação é da JPA e deve ser adicionada apenas nas entidades JPA do projeto(classes Topico, Reposta, Categoria, Usuario, etc.).
Dá uma assistida nessa aula que é explicado sobre a configuração da JPA no projeto: https://cursos.alura.com.br/course/spring-boot-api-rest/task/55820
Refiz o meu código implementei o @Entity e ainda continuou com o erro no console Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2022-04-07 17:32:05.863 ERROR 12368 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: br.com.alura.forum.modelo.StatusTopico
Oi João, parece que ele está achando que a classe StatusTopico é uma entity sem um identificador (campo com a anotação @Id) - mas como na verdade ela é um enum e não uma entity, não precisaria disso....
Verifique se no campo status da classe Topico você colocou a anotação enumerated:
@Enumerated(EnumType.STRING)
private StatusTopico status = StatusTopico.NAO_RESPONDIDO;
Eu adicionei essa anotação e ainda continua com o mesmo erro
João,
Posta aqui o código completo das suas classes.
package br.com.alura.forum.modelo;
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id;
@Entity public class Curso {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String nome;
private String categoria;
public Curso(String nome, String categoria) {
this.nome = nome;
this.categoria = categoria;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Curso other = (Curso) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
}
package br.com.alura.forum.modelo;
import java.time.LocalDateTime;
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne;
@Entity public class Resposta {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String mensagem;
@ManyToOne
private Topico topico;
private LocalDateTime dataCriacao = LocalDateTime.now();
@ManyToOne
private Usuario autor;
private Boolean solucao = false;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Resposta other = (Resposta) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMensagem() {
return mensagem;
}
public void setMensagem(String mensagem) {
this.mensagem = mensagem;
}
public Topico getTopico() {
return topico;
}
public void setTopico(Topico topico) {
this.topico = topico;
}
public LocalDateTime getDataCriacao() {
return dataCriacao;
}
public void setDataCriacao(LocalDateTime dataCriacao) {
this.dataCriacao = dataCriacao;
}
public Usuario getAutor() {
return autor;
}
public void setAutor(Usuario autor) {
this.autor = autor;
}
public Boolean getSolucao() {
return solucao;
}
public void setSolucao(Boolean solucao) {
this.solucao = solucao;
}
}
package br.com.alura.forum.modelo;
import javax.persistence.Entity;
@Entity public enum StatusTopico {
NAO_RESPONDIDO,
NAO_SOLUCIONADO,
SOLUCIONADO,
FECHADO;
}
package br.com.alura.forum.modelo;
import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List;
import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany;
@Entity() public class Topico {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String titulo;
private String mensagem;
private LocalDateTime dataCriacao = LocalDateTime.now();
@Enumerated(EnumType.STRING)
private StatusTopico status = StatusTopico.NAO_RESPONDIDO;
@ManyToOne
private Usuario autor;
@ManyToOne
private Curso curso;
@OneToMany(mappedBy = "topico")
private List<Resposta> respostas = new ArrayList<>();
public Topico(String titulo, String mensagem, Curso curso) {
this.titulo = titulo;
this.mensagem = mensagem;
this.curso = curso;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Topico other = (Topico) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getMensagem() {
return mensagem;
}
public void setMensagem(String mensagem) {
this.mensagem = mensagem;
}
public LocalDateTime getDataCriacao() {
return dataCriacao;
}
public void setDataCriacao(LocalDateTime dataCriacao) {
this.dataCriacao = dataCriacao;
}
public StatusTopico getStatus() {
return status;
}
public void setStatus(StatusTopico status) {
this.status = status;
}
public Usuario getAutor() {
return autor;
}
public void setAutor(Usuario autor) {
this.autor = autor;
}
public Curso getCurso() {
return curso;
}
public void setCurso(Curso curso) {
this.curso = curso;
}
public List<Resposta> getRespostas() {
return respostas;
}
public void setRespostas(List<Resposta> respostas) {
this.respostas = respostas;
}
}
package br.com.alura.forum.modelo;
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id;
@Entity public class Usuario {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String nome;
private String email;
private String senha;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Usuario other = (Usuario) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
}
O Problema está no seu enum StatusTopico:
@Entity
public enum StatusTopico {
NAO_RESPONDIDO,
NAO_SOLUCIONADO,
SOLUCIONADO,
FECHADO;
}
Enum não deve ter a anotação @Entity. Remova essa anotação que o problema se resolverá.