fieldx需要一个类型为y的bean,但找不到

2ul0zpep  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(329)

我试图在我自己的代码中实现这里的代码。但我得到以下错误:

Field confirmationTokenRepository in com.main.mytest.controllers.LoginController required a bean of type 'com.main.mytest.repository.ConfirmationTokenRepository' that could not be found.

Action:

Consider defining a bean of type 'com.main.mytest.repository.ConfirmationTokenRepository' in your configuration.

以下是我的项目结构:

我在类中的代码与链接中提到的完全相同。为了简单起见,我把它们复制到这里:
确认令牌存储库:

package com.main.mytest.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.main.mytest.model.ConfirmationToken;

public interface ConfirmationTokenRepository extends CrudRepository<ConfirmationToken, String> {
    ConfirmationToken findByConfirmationToken(String confirmationToken);
}

确认令牌:

package com.main.mytest.model;    

import java.util.Date;
import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
public class ConfirmationToken {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="token_id")
    private long tokenid;

    @Column(name="confirmation_token")
    private String confirmationToken;

    @Temporal(TemporalType.TIMESTAMP)
    private Date createdDate;

    @OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
    @JoinColumn(nullable = false, name = "user_id")
    private User user;

    public ConfirmationToken() {
    }

    public ConfirmationToken(User user) {
        this.user = user;
        createdDate = new Date();
        confirmationToken = UUID.randomUUID().toString();
    }

    public String getConfirmationToken() {
        return confirmationToken;
    }

    public void setConfirmationToken(String confirmationToken) {
        this.confirmationToken = confirmationToken;
    }

    public Date getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public long getTokenid() {
        return tokenid;
    }

    public void setTokenid(long tokenid) {
        this.tokenid = tokenid;
    }
}

登录控制器:

@Controller
public class LoginController {

@Autowired
private CustomUserDetailsService userService;

@Autowired
ReviewMongoRepository reviewRepository;

@Autowired
ProfileRepository profileRepository;

@Autowired
private UserRepository userRepository;

@Autowired
private ConfirmationTokenRepository confirmationTokenRepository;

@Autowired
private EmailSenderService emailSenderService;

BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

@RequestMapping(value="/forgot-password", method=RequestMethod.POST)
public ModelAndView forgotUserPassword(ModelAndView modelAndView, User user) {
    User existingUser = userRepository.findByEmail(user.getEmail());
    if(existingUser != null) {
        // create token
        ConfirmationToken confirmationToken = new ConfirmationToken(existingUser);

        // save it
        confirmationTokenRepository.save(confirmationToken);

        // create the email
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo(existingUser.getEmail());
        mailMessage.setSubject("Complete Password Reset!");
        mailMessage.setFrom("nairobley@gmail.com");
        mailMessage.setText("To complete the password reset process, please click here: "
        +"http://localhost:8082/confirm-reset?token="+confirmationToken.getConfirmationToken());

        emailSenderService.sendEmail(mailMessage);

        modelAndView.addObject("message", "Request to reset password received. Check your inbox for the reset link.");
        modelAndView.setViewName("successForgotPassword");

    } else {    
        modelAndView.addObject("message", "This email does not exist!");
        modelAndView.setViewName("error");
    }

    return modelAndView;
}

@RequestMapping(value="/confirm-reset", method= {RequestMethod.GET, RequestMethod.POST})
public ModelAndView validateResetToken(ModelAndView modelAndView, @RequestParam("token")String confirmationToken)
{
    ConfirmationToken token = confirmationTokenRepository.findByConfirmationToken(confirmationToken);

    if(token != null) {
        User user = userRepository.findByEmail(token.getUser().getEmail());
        user.setEnabled(true);
        userRepository.save(user);
        modelAndView.addObject("user", user);
        modelAndView.addObject("emailId", user.getEmail());
        modelAndView.setViewName("resetPassword");
    } else {
        modelAndView.addObject("message", "The link is invalid or broken!");
        modelAndView.setViewName("error");
    }

    return modelAndView;
}   

/**
 * Receive the token from the link sent via email and display form to reset password
 */
@RequestMapping(value = "/reset-password", method = RequestMethod.POST)
public ModelAndView resetUserPassword(ModelAndView modelAndView, User user) {
    // ConfirmationToken token = confirmationTokenRepository.findByConfirmationToken(confirmationToken);

    if(user.getEmail() != null) {
        // use email to find user
        User tokenUser = userRepository.findByEmail(user.getEmail());
        tokenUser.setEnabled(true);
        tokenUser.setPassword(encoder.encode(user.getPassword()));
        // System.out.println(tokenUser.getPassword());
        userRepository.save(tokenUser);
        modelAndView.addObject("message", "Password successfully reset. You can now log in with the new credentials.");
        modelAndView.setViewName("successResetPassword");
    } else {
        modelAndView.addObject("message","The link is invalid or broken!");
        modelAndView.setViewName("error");
    }

    return modelAndView;
}

public UserRepository getUserRepository() {
    return userRepository;
}

public void setUserRepository(UserRepository userRepository) {
    this.userRepository = userRepository;
}

public ConfirmationTokenRepository getConfirmationTokenRepository() {
    return confirmationTokenRepository;
}

public void setConfirmationTokenRepository(ConfirmationTokenRepository confirmationTokenRepository) {
    this.confirmationTokenRepository = confirmationTokenRepository;
}

public EmailSenderService getEmailSenderService() {
    return emailSenderService;
}

public void setEmailSenderService(EmailSenderService emailSenderService) {
    this.emailSenderService = emailSenderService;
}
}

我已经尝试添加 @Repository 或者 @Service 在我的课堂上,我在stackoverflow上看到过类似的问题,但没有帮助。
更新1:
以下是主应用程序文件:

package com.main.mytest;

import org.springframework.boot.SpringApplication;
    @SpringBootApplication
    @EnableMongoRepositories("com.main.mytest.repository")
    @ComponentScan(basePackages = {"com.main.mytest"}) // added to solve the porblem but didn't help
    @EntityScan("com.main.mytest.model") // added to solve the porblem but didn't help
public class mainClass{

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

public void run() {
}

@Bean
CommandLineRunner init(RoleRepository roleRepository) {

    return args -> {

        Role adminRole = roleRepository.findByRole("ADMIN");
        if (adminRole == null) {
            Role newAdminRole = new Role();
            newAdminRole.setRole("ADMIN");
            roleRepository.save(newAdminRole);
        }

        Role userRole = roleRepository.findByRole("USER");
        if (userRole == null) {
            Role newUserRole = new Role();
            newUserRole.setRole("USER");
            roleRepository.save(newUserRole);
        }
    };

}

}
以下是配置文件:

@Override
protected void configure(HttpSecurity http) throws Exception {

  http
  .authorizeRequests()
  .antMatchers("/confirm").permitAll()
  .antMatchers("/").permitAll()
  .antMatchers("/login").permitAll()
  .antMatchers("/signup").permitAll()
  .antMatchers("/search").permitAll()
  .antMatchers("/dashboard/**").hasAuthority("ADMIN").anyRequest()
  .authenticated()
  .and().csrf().disable().formLogin().successHandler(customizeAuthenticationSuccessHandler)
  .loginPage("/login")
  .failureUrl("/login?error=true")
  .usernameParameter("email")
  .passwordParameter("password").and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").and().exceptionHandling();
    }
13z8s7eq

13z8s7eq1#

1-添加@repository
2-看看你的@componentscan。如果您的配置文件在另一个文件夹中,而不是在根包下,那么它将找不到组件。
https://reflectoring.io/spring-component-scanning/
====================================================编辑===================
我不知道你做错了什么。我复制了您的部分代码,并重新创建了包结构:

=======代码==========

package com.main.mytest;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.boot.SpringApplication;

@SpringBootApplication
@ComponentScan(basePackages = { "com.main.mytest" }) 
@EntityScan("com.main.mytest.model") 
public class mainClass {

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

    public void run() {
    }

}

================

package com.main.mytest.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.main.mytest.repository.ConfirmationTokenRepository;

@Controller
public class LoginController {

@Autowired
private ConfirmationTokenRepository confirmationTokenRepository;

public ConfirmationTokenRepository getConfirmationTokenRepository() {
    return confirmationTokenRepository;
}

public void setConfirmationTokenRepository(ConfirmationTokenRepository confirmationTokenRepository) {
    this.confirmationTokenRepository = confirmationTokenRepository;
}

}

================

package com.main.mytest.model;

import java.util.Date;
import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
public class ConfirmationToken {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="token_id")
    private long tokenid;

    @Column(name="confirmation_token")
    private String confirmationToken;

    @Temporal(TemporalType.TIMESTAMP)
    private Date createdDate;

    @OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
    @JoinColumn(nullable = false, name = "user_id")
    private User user;

    public ConfirmationToken() {
    }

    public ConfirmationToken(User user) {
        this.user = user;
        createdDate = new Date();
        confirmationToken = UUID.randomUUID().toString();
    }

    public String getConfirmationToken() {
        return confirmationToken;
    }

    public void setConfirmationToken(String confirmationToken) {
        this.confirmationToken = confirmationToken;
    }

    public Date getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public long getTokenid() {
        return tokenid;
    }

    public void setTokenid(long tokenid) {
        this.tokenid = tokenid;
    }
}

=================包com.main.mytest.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="user_id")
    private long user_id;

}

=================包com.main.mytest.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.main.mytest.model.ConfirmationToken;

@Repository
public interface ConfirmationTokenRepository extends CrudRepository<ConfirmationToken, String> {
    ConfirmationToken findByConfirmationToken(String confirmationToken);
}

================

<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 http://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.1.4.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.main.mytest</groupId>
    <artifactId>email-registration</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <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.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
</project>

. ____ _ __ _ _ /\ / ' __ _ () __ __ _ \ \ \ \ ( ( )__ | '_ | '| | ' / ` | \ \ \ \ / )| |)| | | | | || (| | ) ) ) ) ' || .|| ||| |_, | / / / / =========||==============|/=//// :: Spring Boot::(v2.1.4.版本)
2020-11-29 14:27:28.472 info 29216---[main]com.main.mytest.mainclass:在se-00018098上启动mainclass,pid 29216(c:\git\java forgot pswd\target\classes,由ezsusmu在c:\git\java forgot pswd中启动)2020-11-29 14:27:28.475 info 29216---[main]com.main.mytest.mainclass
:未设置活动配置文件,返回默认配置文件:default 2020-11-29 14:27:29.281 info 29216---[main].s.d.r.c.repositoryconfigurationdelegate:在默认模式下引导spring数据存储库。2020-11-29 14:27:29.345信息29216---[main].s.d.r.c.repositoryconfigurationdelegate:在55ms内完成spring数据存储库扫描。找到1个存储库接口。2020-11-29 14:27:29.681信息29216---[main]trationdelegate$beanpostprocessorchecker:bean'org.springframework.transaction.annotation.proxytransactionmanagementconfiguration'类型为[org.springframework.transaction.annotation.proxytransactionmanagementconfiguration$$enhancerbyspringcglib$$c1a84045]的“org.springframework.transaction.annotation.proxytransactionmanagementconfiguration所有BeanPostProcessor(例如:不符合自动代理条件)2020-11-29 14:27:30.682 info 29216---[main]o.s.b.w.embedded.tomcat.tomcatwebserver:tomcat初始化端口:8080(http)2020-11-29 14:27:30.712 info 29216---[main]o.apache.catalina.core.standardservice:starting service[tomcat]2020-11-29 14:27:30.712 info29216---[main]org.apache.catalina.core.standardengine:启动servlet引擎:[apache tomcat/9.0.17]2020-11-29 14:27:30.869信息29216---[
main]o.a.c.c.c.[tomcat].[localhost].[/]:初始化spring embedded webapplicationcontext 2020-11-29 14:27:30.869 info 29216---[main]o.s.web.context.contextloader:根webapplicationcontext:初始化在2334 ms 2020-11-29 14:27:31.125 info 29216---[main]com.zaxxer.hikari.hikaridatasource:hikaripol-1-正在启动。。。2020-11-29 14:27:31.319信息29216---[main]com.zaxxer.hikari.hikaridatasource:hikaripol-1-启动完成。2020-11-29 14:27:31.399信息29216---[main]o.hibernate.jpa.internal.util.loghelper:hhh000204:正在处理persistenceunitinfo[名称:默认…]2020-11-29 14:27:31.496信息29216---[main]org.hibernate.version
:hhh000412:hibernate核心{5.3.9.final}2020-11-29 14:27:31.497信息29216---[main]org.hibernate.cfg.environment
:hh000206:hibernate.properties not found 2020-11-29 14:27:31.674 info 29216---[main]o.hibernate.annotations.common.version:hcann000001:hibernate commons annotations{5.0.4.final}2020-11-29 14:27:31.849 info 29216---[main]org.hibernate.dialect.dialect:hh000400:using dialect:org.hibernate.dialect.h2dialect 2020-11-29 14:27:32.565信息29216---[main]o.h.t.schema.internal.schemacreatorimpl:hh000476:执行导入脚本'org.hibernate.tool.schema.internal.exec。scriptsourceinputnonexistentimpl@587c5c1'2020-11-29 14:27:32.568 info 29216---[main]j.localcontainerentitymanagerfactorbean:初始化了持久化单元的jpa entitymanagerfactory'default'2020-11-29 14:27:33.286信息29216---[main]o.s.s.concurrent.threadpooltaskexecutor:初始化executorservice'applicationtaskexecutor'2020-11-29 14:27:33.375警告29216---[main]awebconfiguration$jpawebmvcconfiguration:spring.jpa.open-in-view默认启用。因此,可以在视图呈现期间执行数据库查询。显式配置spring.jpa.open-in-view以禁用此警告2020-11-29 14:27:33.949 info 29216---[
main]o.s.b.w.embedded.tomcat.tomcatwebserver:tomcat在端口8080(http)上启动,上下文路径为“”2020-11-29 14:27:33.952 info 29216---[main]com.main.mytest.mainclass
:在5.805秒内启动mainclass(jvm运行6.226)
我帮不了你更多。我粘贴的代码使用Java8(您的简化版本)运行良好

相关问题