简体   繁体   English

在Spring Boot中注入自动关联的问题

[英]Issues injecting autowired dependency in Spring Boot

I'm getting a NoSuchBeanDefinitionException for the @Autowired AccountRepository in the code below with the error message: No qualifying bean of type [com.brahalla.PhotoAlbum.dao.AccountRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. 我在下面的代码中收到@Autowired AccountRepository的NoSuchBeanDefinitionException并出现错误消息: No qualifying bean of type [com.brahalla.PhotoAlbum.dao.AccountRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. . I have added the package containing the repository to @ComponentScan but for some reason it is still not seeing it. 我已将包含存储库的软件包添加到@ComponentScan,但是由于某种原因它仍然没有看到它。 Dependency injection works everywhere else in my project, just not in this particular file. 依赖注入在我项目的其他任何地方都有效,只是在这个特定文件中没有。

package com.brahalla.PhotoAlbum.configuration;

import com.brahalla.PhotoAlbum.dao.AccountRepository;
import com.brahalla.PhotoAlbum.domain.entity.Account;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Configuration
@ComponentScan("com.brahalla.PhotoAlbum.dao")
public class GlobalAuthenticationConfiguration extends GlobalAuthenticationConfigurerAdapter {

  @Autowired
  AccountRepository accountRepository;

  @Override
  public void init(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
    authenticationManagerBuilder.userDetailsService(userDetailsService());
  }

  @Bean
  UserDetailsService userDetailsService() {
    return new UserDetailsService() {

      @Override
      public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Account account = accountRepository.findByUsername(username);
        if(account != null) {
          return new User(
            account.getUsername(),
            account.getPassword(),
            true, true, true, true,
            AuthorityUtils.createAuthorityList("USER")
          );
        } else {
          throw new UsernameNotFoundException("could not find the user '" + username + "'");
        }
      }

    };
  }

}

And here is the repository: 这是存储库:

package com.brahalla.PhotoAlbum.dao;

import com.brahalla.PhotoAlbum.domain.entity.Account;

import org.springframework.data.repository.CrudRepository;

public interface AccountRepository extends CrudRepository<Account, Long> {

  public Account findByUsername(String username);

}

And the main application config: 和主要的应用程序配置:

package com.brahalla.PhotoAlbum.configuration;

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

@SpringBootApplication
public class ApplicationConfiguration {

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

}

Here's the full log and stack trace: http://pastebin.com/PKvd8rXV 这是完整的日志和堆栈跟踪: http : //pastebin.com/PKvd8rXV

EDIT Here is the git repository , the code in question is in branch develop . 编辑 这是git存储库 ,有问题的代码在分支develop

The classes with annotations like @controller,@service,@component, @Repository etc will be the candidates for auto wiring and the other classes are not.so consider annotating your class accordingly for proper auto wiring. 带有@ controller,@ service,@ component,@ Repository等批注的类将是自动布线的候选类,而其他类则不是。因此请考虑相应地对您的类进行批注,以进行正确的自动布线。

@Component --> generic stereotype for any Spring-managed component @ Component->任何Spring管理的组件的通用构造

@Repository --> stereotype for persistence layer @Repository- >持久层的构造

@Service --> stereotype for service layer @Service- >服务层的构造

@Controller --> stereotype for presentation layer (spring-mvc) @Controller- >表示层的构造型(spring-mvc)

The following code should work 下面的代码应该工作

 @Repository
 public interface AccountRepository extends CrudRepository<Account, Long> {

  public Account findByUsername(String username);
}

I discovered the solution to the problem, and I just wanted to make sure that I posted it here. 我找到了解决问题的方法,我只是想确保将其发布在这里。

First of all, I moved all of the web configuration options to a single class which extends WebSecurityConfigurerAdapter. 首先,我将所有Web配置选项移到了一个扩展WebSecurityConfigurerAdapter的类中。 Second, I had to change the annotation for the AuthenticationManagerBuilder initialization to @Autowired instead of @Override. 其次,我必须将AuthenticationManagerBuilder初始化的注释更改为@Autowired而不是@Override。 Third, I had to make the UserDetailsService bean public: 第三,我必须将UserDetailsS​​ervice bean公开:

package com.brahalla.PhotoAlbum.configuration;

import com.brahalla.PhotoAlbum.dao.AccountRepository;
import com.brahalla.PhotoAlbum.domain.entity.Account;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

  @Autowired
  AccountRepository accountRepository;

  @Autowired
  public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
    authenticationManagerBuilder
      .userDetailsService(userDetailsService());
  }

  @Override
  protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
      .authorizeRequests()
        .anyRequest().fullyAuthenticated()
      //.and().authorizeUrls()
      /*.and().formLogin()
        .loginPage("/login")
        .permitAll()
      .and().logout()
        .permitAll()*/
      .and().httpBasic()
      .and().csrf()
        .disable();
  }

  @Bean
  public UserDetailsService userDetailsService() {
    return new UserDetailsService() {

      @Override
      public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Account account = accountRepository.findByUsername(username);
        if(account != null) {
          return new User(
            account.getUsername(),
            account.getPassword(),
            true, true, true, true,
            AuthorityUtils.createAuthorityList("USER")
          );
        } else {
          throw new UsernameNotFoundException("could not find the user '" + username + "'");
        }
      }

    };
  }

}

我认为您在ApplicationConfiguration类中缺少@EnableJpaRepositories

Can you post debug logs of the application?. 您可以发布应用程序的调试日志吗? It will give an idea whether the bean was created. 它将给出是否创建该bean的想法。 Try to place componentscan in applicationconfiguration class and mark GlobalAuthenticationConfiguration with @component or relevant annotation 尝试将componentscan放置在applicationconfiguration类中,并使用@component或相关注释标记GlobalAuthenticationConfiguration

Can you try with below snippet : 您可以尝试以下代码段:

package com.brahalla.PhotoAlbum.dao;

import com.brahalla.PhotoAlbum.domain.entity.Account;
import org.springframework.stereotype.Repository;
import org.springframework.data.repository.CrudRepository;

@Repository
public interface AccountRepository extends CrudRepository<Account, Long> {

  public Account findByUsername(String username);

}

Also, annotate your ApplicationConfiguration with @EnableJpaRepositories 另外,用@EnableJpaRepositories注释您的ApplicationConfiguration

1) Could you try to put your class ApplicationConfiguration class in the root package com.brahalla.PhotoAlbum instead of com.brahalla.PhotoAlbum.configuration ? 1)您能否尝试将您的类ApplicationConfiguration类放在根包com.brahalla.PhotoAlbum而不是com.brahalla.PhotoAlbum.configuration

Actually, @SpringBootApplication scans subpackages of where it's located. 实际上, @SpringBootApplication扫描它所在位置的子包。

See Reference Guide 14.2 Locating the main application class 请参见参考指南14.2查找主应用程序类

2) As other said, put @EnableJpaRepositories at your class GlobalAuthenticationConfiguration 2)由于对方说,把@EnableJpaRepositories在你的类GlobalAuthenticationConfiguration

With this two configurations, it should work 使用这两种配置,它应该可以工作

I faced the same issue this issue is exactly due to the Spring Boot ApplicationConfiguration.java being created inside a specific package than in the root. 我遇到了同样的问题,这个问题正是由于Spring Boot ApplicationConfiguration.java是在特定包中而不是在根目录中创建的。 I moved it to root It worked fine. 我将其移至根目录。

ie initially it was in com.myproject.root.config, i moved it to com.myproject.root 即最初是在com.myproject.root.config中,我将其移至com.myproject.root

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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