在spring.io中阅读演示后,我尝试为自己的弹簧启动jpa编写一个演示。但是当我运行演示时它有这些问题。它说在上下文初始化期间遇到异常 - 取消刷新尝试:org.springframework.beans.factory.BeanCreationException:创建名称为' personRepository'的init时出错::init方法的调用失败;嵌套异常是java.lang.IllegalArgumentException:不是托管类型:class com.example.model.Person 。这里是详细信息。我做了一些改变,但我仍然有这个问题。
17:55:40.430 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
17:55:40.432 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
17:55:40.432 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/E:/workspace-sts-3.8.4.RELEASE/demo/target/classes/]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.6.RELEASE)
2017-08-09 17:55:40.645 INFO 10472 --- [ restartedMain] com.example.demo.DemoApplication : Starting DemoApplication on MoriatyC with PID 10472 (E:\workspace-sts-3.8.4.RELEASE\demo\target\classes started by cmh in E:\workspace-sts-3.8.4.RELEASE\demo)
2017-08-09 17:55:40.645 INFO 10472 --- [ restartedMain] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2017-08-09 17:55:40.828 INFO 10472 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@617bc958: startup date [Wed Aug 09 17:55:40 CST 2017]; root of context hierarchy
2017-08-09 17:55:42.196 INFO 10472 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-08-09 17:55:42.208 INFO 10472 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-08-09 17:55:42.208 INFO 10472 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.16
2017-08-09 17:55:42.299 INFO 10472 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-08-09 17:55:42.299 INFO 10472 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1474 ms
2017-08-09 17:55:42.433 INFO 10472 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-08-09 17:55:42.437 INFO 10472 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-08-09 17:55:42.438 INFO 10472 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-08-09 17:55:42.438 INFO 10472 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-08-09 17:55:42.438 INFO 10472 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-08-09 17:55:42.884 INFO 10472 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-08-09 17:55:42.898 INFO 10472 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2017-08-09 17:55:42.950 INFO 10472 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2017-08-09 17:55:42.951 INFO 10472 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-08-09 17:55:42.952 INFO 10472 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2017-08-09 17:55:43.045 INFO 10472 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-08-09 17:55:43.126 INFO 10472 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-08-09 17:55:43.259 INFO 10472 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2017-08-09 17:55:43.264 INFO 10472 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2017-08-09 17:55:43.288 INFO 10472 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-08-09 17:55:43.301 WARN 10472 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'searchController': Unsatisfied dependency expressed through field 'personRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.dao.PersonRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2017-08-09 17:55:43.302 INFO 10472 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-08-09 17:55:43.307 INFO 10472 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2017-08-09 17:55:43.317 INFO 10472 --- [ restartedMain] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-08-09 17:55:43.414 ERROR 10472 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field personRepository in com.example.controller.SearchController required a bean of type 'com.example.dao.PersonRepository' that could not be found.
Action:
Consider defining a bean of type 'com.example.dao.PersonRepository' in your configuration.
这是 PersonRepository.java
package com.example.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.example.model.Person;
public interface PersonRepository extends JpaRepository<Person, Integer> {
List<Person> findByAddress(String address);
Person findByNameAndAddress(String name, String address);
@Query("select p from Person p where p.name = :name and p.address=:address")
Person withNameAndAddressQuery(@Param("name")String name, @Param("address")String address);
Person withNameAndAddressNamedQuery(String name, String address);
}
Person.java
package com.example.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Data
@NamedQuery(name="Person.withNameAndAddressNamedQuery", query = "select p from Person p where p.name=?1 and p.address=?2")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private Integer age;
private String address;
}
SearchController.java
package com.example.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.dao.PersonRepository;
import com.example.model.Person;
@RestController
public class SearchController {
@Autowired
private PersonRepository personRepository;
@RequestMapping("/save")
public Person save(String name, String address, Integer age) {
Person p = personRepository.save(new Person(null, name, age, address));
return p;
}
@RequestMapping("/q1")
public List<Person> q1(String address) {
List<Person> people = personRepository.findByAddress(address);
return people;
}
@RequestMapping("/q2")
public Person q2(String name, String address) {
Person people = personRepository.findByNameAndAddress(name, address);
return people;
}
@RequestMapping("/q3")
public Person q3(String name, String address) {
Person people = personRepository.withNameAndAddressQuery(name, address);
return people;
}
public Person q4(String name, String address) {
Person p = personRepository.withNameAndAddressNamedQuery(name, address);
return p;
}
@RequestMapping("/sort")
public List<Person> sort() {
List<Person> people = personRepository.findAll(new Sort(Direction.ASC,"age"));
return people;
}
@RequestMapping("/page")
public Page<Person> page() {
Page<Person> pagePeople = personRepository.findAll(new PageRequest(1, 2));
return pagePeople;
}
}
这是 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Use MySQL Connector-J -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version><!--$NO-MVN-MAN-VER$ -->
<!-- <scope>provided</scope> -->
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
这是 application.properties
spring.thymeleaf.mode=LEGACYHTML5
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.show-sql=true
spring.jackson.serialization.indent-output=true
这是我的 Application.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@ComponentScan(basePackages = "com.example")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
答案 0 :(得分:2)
您的代码没有问题,问题是您的项目的层次结构,Application类应该在您的模型的父级别,因此它可以扫描您的模型,请检查您的文件。
或者您可以像这样添加@SpringBootApplication
:
@SpringBootApplication(scanBasePackages={"com.example.model"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}