我试图在我自己的代码中实现这里的代码。但我得到以下错误:
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();
}
1条答案
按热度按时间13z8s7eq1#
1-添加@repository
2-看看你的@componentscan。如果您的配置文件在另一个文件夹中,而不是在根包下,那么它将找不到组件。
https://reflectoring.io/spring-component-scanning/
====================================================编辑===================
我不知道你做错了什么。我复制了您的部分代码,并重新创建了包结构:
=======代码==========
================
================
=================包com.main.mytest.model;
=================包com.main.mytest.repository;
================
. ____ _ __ _ _ /\ / ' __ _ () __ __ _ \ \ \ \ ( ( )__ | '_ | '| | ' / ` | \ \ \ \ / )| |)| | | | | || (| | ) ) ) ) ' || .|| ||| |_, | / / / / =========||==============|/=//// :: 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(您的简化版本)运行良好