我的应用: -
@SpringBootApplication
@ComponentScan("fi.ma.vegshopping")
@EnableJpaRepositories("fi.ma.vegshopping")
@EntityScan(basePackages = "fi.ma.vegshopping")
public class VegShoppingApplication {
public static void main(String[] args) {
SpringApplication.run(VegShoppingApplication.class, args);
}
}
问题类: -
import fi.ma.vegshopping.dao.AccountDAO;
import fi.ma.vegshopping.entity.Account;
@Service
public class MyDBAuthenticationService implements UserDetailsService {
@Autowired
private AccountDAO accountDAO;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Account account = accountDAO.findAccount(username);
System.out.println("Account= " + account);
if (account == null) {
throw new UsernameNotFoundException("User " //
+ username + " was not found in the database");
}
// EMPLOYEE,MANAGER,..
String role = account.getUserRole();
List<GrantedAuthority> grantList = new ArrayList<GrantedAuthority>();
// ROLE_EMPLOYEE, ROLE_MANAGER
GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + role);
grantList.add(authority);
boolean enabled = account.isActive();
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
UserDetails userDetails = (UserDetails) new User(account.getUserName(), //
account.getPassword(), enabled, accountNonExpired, //
credentialsNonExpired, accountNonLocked, grantList);
return userDetails;
}
}
AccountDAO类: -
package fi.ma.vegshopping.dao;
import fi.ma.vegshopping.entity.Account;
public interface AccountDAO {
public Account findAccount(String userName );
}
AccountDAOImpl类: -
package fi.ma.vegshopping.impl;
import javax.transaction.Transactional;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import fi.ma.vegshopping.dao.AccountDAO;
import fi.ma.vegshopping.entity.Account;
@Transactional
public class AccountDAOImpl implements AccountDAO {
@Autowired
private SessionFactory sessionFactory;
@Override
public Account findAccount(String userName ) {
Session session = sessionFactory.getCurrentSession();
Criteria crit = session.createCriteria(Account.class);
crit.add(Restrictions.eq("userName", userName));
return (Account) crit.uniqueResult();
}
}
错误: -
申请失败
说明
fi.ma.vegshopping.authentication.MyDBAuthenticationService中的字段accountDAO需要一个类型为&#39; fi.ma.vegshopping.dao.AccountDAO&#39;的bean。无法找到。
动作:
考虑定义类型为&#39; fi.ma.vegshopping.dao.AccountDAO&#39;的bean。在你的配置中。
答案 0 :(得分:1)
问题可能出在包结构上,您需要将@Component
标记为AccountDAOImpl
类(位于 fi.ma.vegshopping.impl
包下),如下所示这样容器就可以扫描并且找到你的注射豆。
@Component //or @Repository
public class AccountDAOImpl implements AccountDAO {
//add your code here
}