java 例外:请考虑在配置中定义类型为的Bean

h5qlskok  于 2023-01-24  发布在  Java
关注(0)|答案(4)|浏览(262)

我对英语不是很熟悉,我会尝试解释这个问题。我正在学习使用spring-boot框架。我正在配置模型部分。所以我使用注解@Entity,@Table创建了数据库表
创建表之后,我为每个表创建了DAO。
我正在遵循教程,但我没有做任何其他事情。
我所做的唯一不同的事情是将这一行添加到“application.properties“文件中,否则应用程序将无法工作(这是在实现模型部件之前)。在创建模型部件之后,我遇到了这个新问题

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

当我运行并生成项目时,由于应用程序无法启动,我得到了以下错误。以下是输出:

:: Spring Boot ::        (v2.2.2.RELEASE)

2020-01-17 10:59:41.645  INFO 12464 --- [           main] c.m.m.MyFirstArtifactApplication         : Starting MyFirstArtifactApplication on SII-AS1 with PID 12464 (C:\Users\g.barbera\Desktop\my-first-artifact\target\classes started by g.barbera in C:\Users\g.barbera\Desktop\my-first-artifact)
2020-01-17 10:59:41.648  INFO 12464 --- [           main] c.m.m.MyFirstArtifactApplication         : No active profile set, falling back to default profiles: default
2020-01-17 10:59:42.500  INFO 12464 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8094 (http)
2020-01-17 10:59:42.507  INFO 12464 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-01-17 10:59:42.507  INFO 12464 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.29]
2020-01-17 10:59:42.590  INFO 12464 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-01-17 10:59:42.590  INFO 12464 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 909 ms
2020-01-17 10:59:42.624  WARN 12464 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myFirstArtifactApplication': Unsatisfied dependency expressed through field 'userDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.myfirstgroup.myfirstartifact.daos.UserDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2020-01-17 10:59:42.626  INFO 12464 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2020-01-17 10:59:42.637  INFO 12464 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-01-17 10:59:42.702 ERROR 12464 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

Field userDao in com.myfirstgroup.myfirstartifact.MyFirstArtifactApplication required a bean of type 'com.myfirstgroup.myfirstartifact.daos.UserDao' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'com.myfirstgroup.myfirstartifact.daos.UserDao' in your configuration.

Process finished with exit code 1

有人能帮帮我吗?
实体:

-用户

package com.myfirstgroup.myfirstartifact.entities;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

@Entity
@Table(name = "users")
@AllArgsConstructor @NoArgsConstructor
        public class User {

        //String ID, String USERNAME, String PASSWORD, String PERMISSION
        @Id                                 //JPA id of the table
        @Column(name = "ID")                //JPA (if column name is different from variable name)
        @NotEmpty @NotBlank @NotNull        //Lombok annotation
        @Getter @Setter                     //JSR-303 Validation
        private String id;

        @Column(name = "USERNAME")          //JPA (if column name is different from variable name)
        @NotEmpty @NotBlank @NotNull        //Lombok annotation
        @Getter @Setter                     //JSR-303 Validation
        private String username;

        @Column(name = "PASSWORD")          //JPA (if column name is different from variable name)
        @NotEmpty @NotBlank @NotNull        //Lombok annotation
        @Getter @Setter                     //JSR-303 Validation
        private String password;

        @Column(name = "PERMISSION")        //JPA (if column name is different from variable name)
        @NotEmpty @NotBlank @NotNull        //Lombok annotation
        @Getter @Setter                     //JSR-303 Validation
        private String permission;

    }

-账户

package com.myfirstgroup.myfirstartifact.entities;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

@Entity
@Table(name = "accounts")
@AllArgsConstructor @NoArgsConstructor

public class Account {

    //String ID, String FK_USER, Double TOTAL
    @Id                             //JPA id of the table
    @Column(name = "ID")            //JPA (if column name is different from variable name)
    @NotNull @NotBlank @NotEmpty    //Lombok annotation
    @Getter @Setter                 //JSR-303 Validation
    private String id;

    @Column(name = "FK_USER")       //JPA (if column name is different from variable name)
    @NotNull @NotBlank @NotEmpty    //Lombok annotation
    @Getter @Setter                 //JSR-303 Validation
    private String fkUser;

    @Column(name = "TOTAL")         //JPA (if column name is different from variable name)
    @Getter @Setter                 //JSR-303 Validation
    private Double total;
}

*操作

package com.myfirstgroup.myfirstartifact.entities;

  import lombok.AllArgsConstructor;
  import lombok.Getter;
  import lombok.NoArgsConstructor;
  import lombok.Setter;
  import javax.persistence.*;
  import javax.validation.constraints.NotBlank;
  import javax.validation.constraints.NotEmpty;
  import javax.validation.constraints.NotNull;
  import java.util.Date;

 @Entity
 @Table(name = "operations")
 @AllArgsConstructor @NoArgsConstructor
 public class Operation {
      //String ID, Date DATE, Double Value, String DESCRIPTION, String FK_ACCOUNT1, String FK_ACCOUNT2

@Id                             //JPA id of the table
@Column(name ="ID")             //JPA (if column name is different from variable name)
@Getter @Setter                 //JSR-303 Validation
@NotEmpty @NotNull @NotBlank    //Lombok annotation
private String id;

@Column(name ="DATE")           //JPA (if column name is different from variable name)
@Getter @Setter                 //JSR-303 Validation
private Date date;              //Lombok annotation

@Column(name ="DESCRIPTION")    //JPA (if column name is different from variable name)
@Getter @Setter                 //JSR-303 Validation
private String description;

@Column(name ="VALUE")          //JPA (if column name is different from variable name)
@Getter @Setter                 //JSR-303 Validation
@NotNull                        //Lombok annotation
private Double value;

@Column(name ="FK_ACCOUNT1")    //JPA (if column name is different from variable name)
@Getter @Setter                 //JSR-303 Validation
@NotEmpty @NotNull @NotBlank    //Lombok annotation
private String fkAccount1;

@Column(name ="FK_ACCOUNT2")    //JPA (if column name is different from variable name)
@Getter @Setter                 //JSR-303 Validation
private String fkAccount2;

@PrePersist
void getTimeOperation(){
    this.date = new Date();
}

}
道:

-用户道

package com.myfirstgroup.myfirstartifact.daos;

import com.myfirstgroup.myfirstartifact.entities.User;
import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.stereotype.Repository;

import java.util.Optional;

public interface UserDao extends JpaRepository<User, String> {

    Optional<User> findById(String id);
}

*会计道

package com.myfirstgroup.myfirstartifact.daos;

  import com.myfirstgroup.myfirstartifact.entities.Account;
  import org.springframework.data.jpa.repository.JpaRepository;
  import org.springframework.data.jpa.repository.Query;
  import org.springframework.data.repository.query.Param;
  import org.springframework.stereotype.Repository;

  import java.util.List;

  public interface AccountDao extends JpaRepository<Account, String> {
@Query(value = "SELECT * FROM accounts WHERE FK_USER=:user", nativeQuery = true)
List<Account> getAllAccountPerUser(@Param("user")String user);
List<Account> findByFkUser(String fkUser);

}

*道行动

package com.myfirstgroup.myfirstartifact.daos;

import com.myfirstgroup.myfirstartifact.entities.Operation;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

public interface OperationDao extends JpaRepository<Operation,String> {
@Query(value = "SELECT * FROM operations WHERE FK_ACCOUNT1:=account OR FK_ACCOUNT2:=account", nativeQuery = true)
List<Operation> findAllOperationByAccount(@Param("account") String account);

}
ArtifactApplication.java:

package com.myfirstgroup.myfirstartifact;

import com.myfirstgroup.myfirstartifact.daos.AccountDao;
import com.myfirstgroup.myfirstartifact.daos.OperationDao;
import com.myfirstgroup.myfirstartifact.daos.UserDao;
import com.myfirstgroup.myfirstartifact.entities.Account;
import com.myfirstgroup.myfirstartifact.entities.Operation;
import com.myfirstgroup.myfirstartifact.entities.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import java.util.Date;

@SpringBootApplication


public class MyFirstArtifactApplication implements CommandLineRunner{

    @Autowired
    UserDao userDao;

    @Autowired
    AccountDao accountDao;

    @Autowired
    OperationDao operationDao;


    private static final Logger log =  LoggerFactory.getLogger(MyFirstArtifactApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(MyFirstArtifactApplication.class, args);
        System.out.println("ciao");
    }

    @Override
    public void run(String... strings) throws Exception{
        log.info("ciao23");

        userDao.save(new User("AAABBB12C456D", "Aaaaaaa", "bbbbbbb", "user"));
        userDao.save(new User("RSSMRA85T10A562S", "Mario Rossi", "abba", "user"));
        userDao.save(new User("PLLPNC82B02G224Z", "Pinco Pallino", "salutpass", "user"));

        accountDao.save(new Account("account_number_1","AAABBB12C456D",3000.00));
        accountDao.save(new Account("account_number_2","AAABBB12C456D",4000.00));
        accountDao.save(new Account("account_number_3","RSSMRA85T10A562S",7000.00));
        accountDao.save(new Account("account_number_4","PLLPNC82B02G224Z",2000.00));
        accountDao.save(new Account("account_number_5","PLLPNC82B02G224Z",8000.00));

        operationDao.save(new Operation("3452",new Date(),"Bonifico Bancario",100.00,"account_number_1","account_number_3"));
        operationDao.save(new Operation("3453",new Date(),"Pagamento Tasse",-100.00,"account_number_2","account_number_5"));
        operationDao.save(new Operation("3454",new Date(),"Postagiro",230.00,"account_number_3","account_number_4"));
        operationDao.save(new Operation("3455",new Date(),"Vaglia Postale",172.00,"account_number_1","account_number_5"));
        operationDao.save(new Operation("3456",new Date(),"Acquisto Azioni",-3400.00,"account_number_2","account_number_4"));
        operationDao.save(new Operation("3457",new Date(),"Vendita Azioni",100.00,"account_number_2","account_number_3"));
        operationDao.save(new Operation("3458",new Date(),"Prelevamento",-100.00,"account_number_3",""));
        operationDao.save(new Operation("3459",new Date(),"Deposito",1100.00,"account_number_5","account_number_1"));
    }
}

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.myfirstgroup</groupId>
    <artifactId>my-first-artifact</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>my-first-artifact</name>
    <description>Demo project for Spring Boot</description>

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
        </dependency>

    </dependencies>

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

</project>

application.properties:

server.port=8094
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
lpwwtiir

lpwwtiir1#

您需要使用@Repository注解来注解UserDao

fbcarpbf

fbcarpbf2#

UserDao应为Spring Bean。要使其成为Spring Bean,请使用注解**@Repository或@Component**

voase2hg

voase2hg3#

创建@Controller类和@Autowire你的Dao的在那里(但使用构造函数)... Sping Boot 是一个预配置的Spring mvc..所以模型-是你的实体,控制器-?,你可以使用@service/ @Component 也.和使用@Repository对UserDao

tgabmvqs

tgabmvqs4#

您正在主类中使用@Autowired UserDao,这就是原因。
试试看:
1.在UserDao中添加@Repository
1.然后,使用@PostConstruct注解MyFirstArtifactApplication中的run方法。
如果以上方法不起作用,请尝试将主类更改为:

@SpringBootApplication
public class MyFirstArtifactApplication {

    @Autowired
    UserDao userDao;

    private static final Logger log =  LoggerFactory.getLogger(MyFirstArtifactApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(MyFirstArtifactApplication.class, args);
        System.out.println("ciao");
    }

    @PostConstruct 
    public void setUpData(String... strings) throws Exception {
        log.info("ciao23");
        userDao.save(new User("AAABBB00A01A123A", "A B", "AA","user"));
        userDao.save(new User("RSSMRA85T10A562S", "M R","ab", "user"));
    }
 }

相关问题