0

I'm learning Spring Boot and I get this error message:

Parameter 0 of constructor in com.example.demo.appuser.AppUserService required a bean of type 'com.example.demo.appuser.AppUserRepository' that could not be found.

Here is my AppUserService

package com.example.demo.appuser;

import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class AppUserService implements UserDetailsService {

    private final static String USER_NOT_FOUND_MSG =
            "user with email %s not found";

    @Autowired
    private AppUserRepository appUserRepository;


    @Override
    public UserDetails loadUserByUsername(String email)
            throws UsernameNotFoundException {
        return appUserRepository.findByEmail(email)
                .orElseThrow(() ->
                        new UsernameNotFoundException(
                                String.format(USER_NOT_FOUND_MSG, email)));
    }
}

And here is my AppUserRepository

package com.example.demo.appuser;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Repository
@Transactional(readOnly = true)
public interface AppUserRepository
        extends JpaRepository<AppUser, Long> {

    Optional<AppUser> findByEmail(String email);
}

Update, here is my config file

package com.example.demo.security.config;

import com.example.demo.appuser.AppUserService;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@AllArgsConstructor
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final AppUserService appUserService;
    private final BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                    .antMatchers("/api/v*/registration/**")
                    .permitAll()
                .anyRequest()
                .authenticated().and()
                .formLogin();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProvider());
    }

    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider(){
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();

        provider.setPasswordEncoder(bCryptPasswordEncoder);
        provider.setUserDetailsService(appUserService);
        return  provider;
    }
}

Update 2 my stacktrace

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

Description:

Parameter 0 of constructor in com.example.demo.appuser.AppUserService required a bean named 'entityManagerFactory' that could not be found.


Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.


Process finished with exit code 1

Thats all what i get

Update 3: link to my package structure: https://i.stack.imgur.com/4dt7N.jpg

Update 4 DemoApllication:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@SpringBootApplication(scanBasePackages = "com.example")
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class DemoApplication {

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

}

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.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>16</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

application.yml:

server:
  error:
    include-message: always
    include-binding-errors: always

spring:
  datasource:
    password:
    url: jdbc:postgresql://localhost:5432/registration
    username:
  jpa:
    hibernate:
      ddl-auto: create-drop
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect
        format_sql: true
    show-sql: true

  mail:
    host: localhost
    port: 1025
    username: hello
    password: hello

    properties:
      mail:
        smtp:
          ssl:
            trust: "*"
          auth: true
          starttls:
            enable: true
          connectiontimeout: 5000
          timeout: 3000
          writetimeout: 5000

If anybody know whats the problem, please help me

  • 1
    What does your Spring configuration look like? For some reason `AppUserRepository` isn't included in your Spring application context, but without knowing more details about how you are configuring Spring, it's not possible to tell why. – Jesper Jun 11 '21 at 08:28
  • Assuming you are really using plain Spring and not Spring Boot, you should have an `@EnableJpaRepositories` annotation on a/your `@Configuration` class, so that Spring Data can properly detect the interface and create the necessary beans. I would strongly suggest to remove `@Repository` as it doesn' t add anything (putting that on an interface makes no sense). Finally as you are using Lombok to create a constructor you should remove the `@Autowired` as Spring will automatically use the single arg constructor for dependency injection. – M. Deinum Jun 11 '21 at 09:33
  • I added my config class, I hope thats the right one, and I made a mistake I am using Spring Boot not Spring –  Jun 11 '21 at 18:22
  • Can you provide the full stacktrace? – gtiwari333 Jun 11 '21 at 18:31
  • It will be a noob question but stacktrace is what the console print out? –  Jun 11 '21 at 18:36
  • no. console contains several logs too. Stacktrace is where it shows how and where the error happened – gtiwari333 Jun 11 '21 at 18:40
  • you can post everything that you see in console for now – gtiwari333 Jun 11 '21 at 18:40
  • read this later.. https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors – gtiwari333 Jun 11 '21 at 18:41
  • also post a screenshot of your package structure showing where the @SpringBootApplication is located – gtiwari333 Jun 11 '21 at 18:42
  • I added my stacktrace but i can't add image to the post –  Jun 11 '21 at 18:48
  • Have you added @EnableJPARepositories annotation on any of your configuration files? – Felipe Bonfante Jun 11 '21 at 18:58
  • @FelipeBonfante I tried but I get the same error –  Jun 11 '21 at 19:04
  • 1
    https://docs.spring.io/spring-boot/docs/current/reference/html/using.html#using.structuring-your-code.locating-the-main-class Unless you can provide un the steps to reproduce, my guess is your `@SpringBootApplication` is defined in a wrong folder. Or `@EnableJPARepositories` annotation has invalid package name in it – gtiwari333 Jun 11 '21 at 19:07
  • As @gtiwari333 said, probably you need to provide the correct package for enable jpa repositores annotation or your springBootApplication is on another folder – Felipe Bonfante Jun 11 '21 at 19:14
  • @gtiwari333 I added a link to my package structure –  Jun 11 '21 at 19:15
  • It looks the DemoApplication class is under security folder, Move it under com.example.demo and see what happens – gtiwari333 Jun 11 '21 at 19:17
  • DemoApplication class is in com.example.demo but i get a new error, I added to the post –  Jun 11 '21 at 19:19
  • Can you post your DemoApplication and the pom.xml or build.gradle? Also, I didn't see your new error on the post. – gtiwari333 Jun 11 '21 at 19:22
  • also the application.yml/properties – gtiwari333 Jun 11 '21 at 19:22
  • The new error is very similar to the previous one, its only print entityManagerFactory except AppUserRepository –  Jun 11 '21 at 19:24
  • I added the required files –  Jun 11 '21 at 19:27
  • Any reason to exclude the `DataSourceAutoConfiguration.class`? Also I didn't see username and password on your datasource config – gtiwari333 Jun 11 '21 at 19:31
  • 1
    That exclude was the problem, It's working now. Thank you so much –  Jun 11 '21 at 19:38

1 Answers1

0

as @Jesper's answered, Your AppUserRepository isn't in spring application context. please check your spring main class, and make sure an annotation named @EntityScan (${RepositoryPackagePrefix}) above Class. eg : @EntityScan("com.Example").

  • 1
    `@EntityScan` won't work, and it isn't a Spring annotation but rather a Spring Boot annotation which won't be available in a plan Spring application. Nor would it solve this as it is for scanning entities and not repositories. – M. Deinum Jun 11 '21 at 09:32
  • Sorry, i got it wrong。try @SpringBootApplication(scanBasePackages = "com.example") annotation in your main class. and make sure your repository included in that path and don't forget @EnableJpaRepositories("com.example") in your configuration class –  Jun 11 '21 at 09:46
  • Again the question is about Spring **not** Spring Boot, trying to throw Spring Boot annotations at a non Spring Boot application will not do a thing (as I already pointed out). – M. Deinum Jun 11 '21 at 11:19
  • I updated my question, I'm using Spring Boot not Spring, sorry it was my bad –  Jun 11 '21 at 18:23
  • Instead of just specifying `@AllArgsConstructor` can you also add `@NoArgsConstructor` ? – Amit Mishra Jul 07 '21 at 06:56