简体   繁体   中英

Exception: Consider defining a bean of type in your configuration

I'm not very familiar with English. I will try to explain the problem. I am learning to use spring-boot framework. I'm configuring the model part. So I created the database tables using annotations @Entity, @Table

After I created the tables, I created DAO for each one.

I am following a tutorial, but I am not doing anything other than it.

The only different thing I did was add this line to the "application.properties" file otherwise the application would not work (this before implementing the model part) After creating the model part I encountered this new problem

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

When I run and build the project I get the following error because the application fails to start. This is the output:

 :: 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

Can anyone help me?

Entities:

- User

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;

    }

- Account

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;
}
  • Opearation

     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(); }

    }

Daos:

-UserDao

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);
}
  • AccountDao

     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);

    }

  • OperationDao

    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

你需要注释UserDao@Repository注解。

UserDao should be a spring bean. In order to make it a spring bean use annotation @Repository or @Component

You are using @Autowired UserDao in main class, which is the cause.

Try :

  1. Adding @Repository in UserDao
  2. Then, annotate run method in MyFirstArtifactApplication , with @PostConstruct .

If the above does not work, then try changing your main class to :

@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"));
    }
 }

create @Controller class and @Autowire yours Dao's in there (but use a constructor)... Spring boot is a preconfigurated spring mvc .. so model - is yours Entity , controller - ? ,you can use @service/@component also. and use @Repository on UserDao

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM