java-Spring Data JPA错误创建bean
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java-Spring Data JPA错误创建bean,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含7944字,纯文字阅读大概需要12分钟。
内容图文
![java-Spring Data JPA错误创建bean](/upload/InfoBanner/zyjiaocheng/669/61628bdd884f482897bf6fb968a4175d.jpg)
让我向您介绍我的代码,然后我将提一个问题.
首先-结构:
人.java
package com.test.business;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "person")
public class Person {
@Id
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
public Person(){
}
public Person(int id, String name) {
this.id = id;
this.name = name;
}
//getters and setters
}
PersonRepository.java
package com.test.repository;
import com.test.business.Person;
import org.springframework.data.repository.CrudRepository;
public interface PersonRepository extends CrudRepository<Person, Long> {
}
PersonService.java
package com.test.service;
import com.test.business.Person;
import com.test.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PersonService{
@Autowired
private PersonRepository personRepository;
public void addNewPerson(){
personRepository.save(new Person(2, "Test2"));
}
}
PersonController.java
package com.test.controller;
import com.test.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class PersonController {
@Autowired
private PersonService personService;
@GetMapping(value="/")
@ResponseBody
public String printWelcome() {
personService.addNewPerson();
return "home";
}
MyWebInitializer.java
package com.test.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MyWebInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { RootConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
WebConfig.java
package com.test.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc
@Configuration
@ComponentScan({ "com.test.controller" })
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver
= new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
RootConfig.java
package com.test.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories( basePackages = {"com.test.repository"})
@EnableTransactionManagement
@ComponentScan(basePackages = {"com.test.service", "com.test.repository", "com.test.controller", "com.test.business"})
public class RootConfig {
@Autowired
private DataSource dataSource;
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://localhost:5432/postgres");
dataSource.setUsername("postgres");
dataSource.setPassword("postgres");
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabase(Database.POSTGRESQL);
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan(getClass().getPackage().getName());
factory.setDataSource(dataSource());
factory.setJpaProperties(jpaProperties());
return factory;
}
private Properties jpaProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
properties.put("hibernate.show_sql", "true");
return properties;
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory().getObject());
return txManager;
}
}
build.gradle
plugins {
id 'java'
}
apply plugin: 'war'
group 'testApp'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile 'org.apache.tomcat:tomcat-catalina:9.0.10'
compile 'org.springframework.boot:spring-boot-starter-data-jpa:2.0.3.RELEASE'
compile 'org.hibernate:hibernate-core:5.3.2.Final'
compile 'org.springframework.data:spring-data-jpa:2.0.9.RELEASE'
compile 'org.postgresql:postgresql:42.2.3'
compile 'org.springframework:spring-webmvc:5.0.7.RELEASE'
compile 'org.hibernate:hibernate-entitymanager:5.3.3.Final'
compile 'javax.xml.bind:jaxb-api:2.3.0'
}
在构建此项目时,没有错误,但是当我尝试运行时,此应用程序控制台显示错误:
ERROR org.springframework.web.context.ContextLoader – Context
initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name ‘personService’: Unsatisfied dependency
expressed through field ‘personRepository’; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name ‘personRepository’: Invocation of init method
failed; nested exception is java.lang.IllegalArgumentException: Not a
managed type: class com.test.business.Person
(…)
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name ‘personRepository’: Invocation of init
method failed; nested exception is java.lang.IllegalArgumentException:
Not a managed type: class com.test.business.Person
(…)
Caused by: java.lang.IllegalArgumentException: Not a managed type:
class com.test.business.Person
这是为什么?为什么无法创建personService bean?我在Person.java中具有@Entity,包括自动装配,RootConfig包含@ComponentScan
@ComponentScan(basePackages = {"com.test.service", "com.test.repository", "com.test.controller", "com.test.business"})
您可以给我一些建议来解决我的问题吗?
解决方法:
上下文初始化时,Spring无法将您的实体类标识为有效实体.为使它们有效,请尝试以下方法之一:
>更改factory.setPackagesToScan(getClass().getPackage().getName());到factory.setPackagesToScan(“ com.test.business”);.否则,com.test.config包将用于实体扫描.
>尝试删除factory.setPackagesToScan(getClass().getPackage().getName());并将@EntityScan(“ com.test.business”)放在您的RootConfig.java之上
另见Difference between @EntityScan and @ComponentScan
内容总结
以上是互联网集市为您收集整理的java-Spring Data JPA错误创建bean全部内容,希望文章能够帮你解决java-Spring Data JPA错误创建bean所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。