自动装配:预计至少有一个bean可以作为此依赖关系的autowire候选者

时间:2017-05-24 05:29:39

标签: java spring exception spring-boot autowired

好的,我知道围绕同一主题提出了很多问题。但我似乎无法做任何事情。也许我还没有完全理解汽车接线概念。 我的问题: 我能够进入所需的页面,但每当我点击任意按钮执行操作时,我会得到Null指针异常,这似乎很明显,因为我不认为spring能够正确映射所需的bean。

所以,当我添加@ autowired = true时,它会给我上面给出的异常。 我不确定需要做什么。希望有人可以帮我解决这个问题。也会喜欢一个解释:) 代码:

@Entity
@Table(name="userDetails")
public class UserDetailModel {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int user_id;
public String password;
public String user_name;
public String active_status;

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getUser_name() {
    return user_name;
}

public void setUser_name(String user_name) {
    this.user_name = user_name;
}

public int getUser_id() {
    return user_id;
}

public void setUser_id(int user_id) {
    this.user_id = user_id;
}

public String getActive_status() {
    return active_status;
}

public void setActive_status(String active_status) {
    this.active_status = active_status;
}

}

控制器:

@RestController
public class UserDetailController {

 private Logger logger = (Logger) LoggerFactory.getLogger(UserDetailController.class);
 @Autowired(required = true)
private UserRepository userRepository;

@RequestMapping(value="/login", method = RequestMethod.POST)
public @ResponseBody String addNewUser (@RequestBody UserDetailModel user) {
    // @ResponseBody means the returned String is the response, not a view name
    // @RequestParam means it is a parameter from the GET or POST request

    logger.debug("in controller");
    UserDetailModel userDtl = new UserDetailModel();
    userDtl.setUser_id(user.user_id);
    userDtl.setUser_name(user.user_name);
    userDtl.setActive_status(user.active_status);
    userDtl.setPassword(user.password);

    userRepository.save(userDtl);
    return "Saved";
}

}

存储库:

@Repository
public interface UserRepository extends CrudRepository<UserDetailModel,         Long> {}

堆栈追踪:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDetailController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.springBoot.usl.repo.UserRepository com.springBoot.usl.controller.UserDetailController.userRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.springBoot.usl.repo.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:120)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:683)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:313)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:944)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:933)
at com.springBoot.usl.controller.WebAppInitializer.main(WebAppInitializer.java:18)

根据回复解决答案: 我根据Jay和Luay的答案做了一些修改。并在我的ApplicationConfig文件中更改了注释:

@Configuration
@ComponentScan("my.basepackage.*")
@EnableJpaRepositories(basePackages = {"my.basepackage.*"})
@EntityScan("my.basepackage.*")
@EnableAutoConfiguration

希望这对某人有所帮助。

但我不确定*是否是正确的方法。

5 个答案:

答案 0 :(得分:4)

我能够在注释方面进行一些更改来运行你的应用程序。

我使用了相同的类。请参阅下面使用的结构和配置。 Directory Structure

我使用了以下包,并添加了你的课程,
  com.rcmutha.usl.controller
 的 com.rcmutha.usl.repository

@SpringBootApplication
@ComponentScan({"com.rcmutha*"})
@EntityScan("com.rcmutha*")
@EnableJpaRepositories("com.rcmutha*")
public class Application {

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

完整代码: click here for code

答案 1 :(得分:1)

我认为您的应用程序无法扫描UserRepository类,如果您使用的是Spring Boot,那么您应该将主类放在包层次结构之上。

您还应该使用@EnableJpaRepositories并告诉它您的存储库的基本软件包以启用存储库功能

@EnableJpaRepositories(basePackages ={"com.springBoot.usl.repo"})

答案 2 :(得分:0)

您需要在配置类中启用JPA存储库,指定包含存储库的包,如下所示

@Configuration
@EnableJpaRepositories(basePackages = {
    "com.springBoot.usl.repo"
})
public class ApplicationConfig {

}

ApplicationConfig示例:

@Configuration
@EnableJpaRepositories(basePackages = {"com.springBoot.usl.repo"})
@EnableTransactionManagement
public class ApplicationConfig {

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/xxxx");
        dataSource.setUsername("xxxx");
        dataSource.setPassword("xxxx");

        return dataSource;
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("xx.xxxx.xxxx.xxxx.domain");
        factory.setDataSource(dataSource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory());
        return txManager;
    }

答案 3 :(得分:0)

@ComponentScan("org.my.pkg")根本没有在当前的Spring Context中定义。 确保您的类在Spring扫描的包中定义。您需要在Configuration类中使用@SpringBootApplication来使Spring扫描包。

如果您正在使用Spring Boot,请确保在其他类上方的根程序包中找到使用@ComponentScan注释的主应用程序类,因为它包含{{1}}。

答案 4 :(得分:0)

我知道问题已经解决,但是由于像我这样的人可能遇到问题,因此我决定分享我的问题和解决方案。 我得到了完全相同的错误消息,但问题是在类中缺少@Service注释,因此该类型的对象无法自动装配。放置此注释后,一切正常。

下面是提到的类的对象:

@Autowired
private JwtUserDetailsService jwtUserDetailsService;

仅此注释引起了相同的问题,并且可能会被忽略:

@Service  // annotation that was missing
public class JwtUserDetailsService implements UserDetailsService { ...