当前位置: 首页 > 知识库问答 >
问题:

注释@AutoWired出现问题。如何决定?

潘银龙
2023-03-14

有一个代码:

package com.example.sweater3.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Message {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String text;
    private String tag;

    public Message() {
    }

    public Message(String text, String tag) {
        this.text = text;
        this.tag = tag;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }

    public Integer getId() {
        return id;
    }

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

    public String getTag() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }
}

_

package com.example.sweater3.repos;

import com.example.sweater3.domain.Message;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface MessageRepo extends CrudRepository<Message, Long> {

    List<Message> findByTag(String tag);
}

__

package com.example.sweater3;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
package com.example.sweater3;

import com.example.sweater3.repos.MessageRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class GreetingController {

    @Autowired
    private MessageRepo messageRepo;
}
<?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>sweater3</artifactId>
    <version>1.0-SNAPSHOT</version>


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mustache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>javax.persistence-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
            <version>2.1.9.RELEASE</version>
        </dependency>

    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
 :: Spring Boot ::        (v2.0.0.RELEASE)

2019-10-30 21:28:05.351  INFO 4044 --- [  restartedMain] com.example.sweater3.Application         : Starting Application on IlyaPC with PID 4044 (D:\EPAM\1Spring2019(04.19-09.19)\My\TEST\5October\30\sweater3\target\classes started by Ilya in D:\EPAM\1Spring2019(04.19-09.19)\My\TEST\5October\30\sweater3)
2019-10-30 21:28:05.354  INFO 4044 --- [  restartedMain] com.example.sweater3.Application         : No active profile set, falling back to default profiles: default
2019-10-30 21:28:05.779  INFO 4044 --- [  restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@7f8d5a6e: startup date [Wed Oct 30 21:28:05 MSK 2019]; root of context hierarchy
2019-10-30 21:28:10.905  INFO 4044 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-10-30 21:28:10.967  INFO 4044 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-10-30 21:28:10.968  INFO 4044 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.28
2019-10-30 21:28:10.985  INFO 4044 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : 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\jdk1.8.0_212\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files\Java\jdk-12.0.1\bin\;C:\Program Files\Java\jdk1.8.0_212\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Program Files\Java\jre1.8.0_221\bin;C:\Users\Илья\AppData\Roaming\npm;.]
2019-10-30 21:28:11.243  INFO 4044 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-10-30 21:28:11.244  INFO 4044 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 5477 ms
2019-10-30 21:28:11.646  INFO 4044 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2019-10-30 21:28:11.656  INFO 4044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-10-30 21:28:11.657  INFO 4044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-10-30 21:28:11.657  INFO 4044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-10-30 21:28:11.657  INFO 4044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2019-10-30 21:28:11.741  WARN 4044 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'greetingController': Unsatisfied dependency expressed through field 'messageRepo'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.sweater3.repos.MessageRepo' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2019-10-30 21:28:11.745  INFO 4044 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2019-10-30 21:28:11.780  INFO 4044 --- [  restartedMain] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-10-30 21:28:12.257 ERROR 4044 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field messageRepo in com.example.sweater3.GreetingController required a bean of type 'com.example.sweater3.repos.MessageRepo' that could not be found.


Action:

Consider defining a bean of type 'com.example.sweater3.repos.MessageRepo' in your configuration.

附注。代码是尽可能简化的,因为我删除了额外的部分,以便它们不会干扰阅读代码和杂乱的审查。

UPD:

对评论的答复:

添加后出现以下错误-

2019-10-30 21:46:01.861  WARN 2716 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'inMemoryDatabaseShutdownExecutor' defined in class path resource [org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.class]: Unsatisfied dependency expressed through method 'inMemoryDatabaseShutdownExecutor' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
2019-10-30 21:46:01.885  INFO 2716 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2019-10-30 21:46:01.943  INFO 2716 --- [  restartedMain] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-10-30 21:46:01.970 ERROR 2716 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified and no embedded datasource could be auto-configured.

Reason: Failed to determine a suitable driver class


Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

共有1个答案

郑西岭
2023-03-14

必须在应用程序中启用存储库:

@SpringBootApplication
@EnableJpaRepositories

public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

还要确保添加:

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-jpa</artifactId>       
</dependency>

更新:必须配置数据库连接和驱动程序。H2示例(内存数据库中)

<dependency>
     <groupId>com.h2database</groupId>
     <artifactId>h2</artifactId>
     <scope>runtime</scope>
</dependency>
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
 类似资料:
  • 本文向大家介绍解决JS外部文件中文注释出现乱码问题,包括了解决JS外部文件中文注释出现乱码问题的使用技巧和注意事项,需要的朋友参考一下 问题描述 中文乱码在Java Web开发中经常出现,这是由于不同的部分编码不一样造成的,一般在开发中,我们把所有能设编码的地方,全部设置成UTF-8,但是有时候还是会出现乱码的情况。在开发中,一般把js代码从html中抽出来,放到一个js文件中,js文件中包含中文

  • 我试图构建我的第一个Spring MVC项目,我一直在阅读大量的教程,观看视频等...但我面临着这个问题: 说明服务器遇到一个内部错误,使其无法满足此请求。 例外 servletException:servlet的servlet.init()springDispatcherServlet抛出异常

  • 本文向大家介绍解决wx.onMenuShareTimeline出现的问题,包括了解决wx.onMenuShareTimeline出现的问题的使用技巧和注意事项,需要的朋友参考一下 wx.onMenuShareTimeline使用注意事项 我在开发测试过程中,发现使用wx.onMenuShareTimeline无效果,没有显示我定义的图片、title和链接,经过调试发现原因如下: 1.图片大小要大于

  • 如果我有用@component注释标记的bean。而是不同文件夹中的两个bean。一个在com.mycompany.core.bean1中,另一个在com.mycompany.dao.bean2中。当我试图在Bean2中自动连接bean1时,就像: 我需要在bean2中导入带有bean1的包吗?还是它会自己扫描它? UPD:我知道同名的问题。但问题是完全不同的。所以请注意我的问题,如果你现在它,不

  • 本文向大家介绍详解@Autowired(required=false)注入注意的问题,包括了详解@Autowired(required=false)注入注意的问题的使用技巧和注意事项,需要的朋友参考一下 1、前言 在使用spring开发过程中,我们基本上都是使用@Autowired这个注解,用来注入已有的bean。但是有些时候,会注入失败。当我们加上参数(required=false)就能解决。今