Solucionado (ver solução)
Solucionado
(ver solução)
2
respostas

O @autowired não está injetando o meu UsuarioDAO após configurar o Spring security

Fiz a implementação do Spring Security conforme o Instrutor mandou, mas ao rodar recebo a mensagem de que o UsuarioDAO não pode ser injetado:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'br.com.kemedico.daos.UsuarioDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1700)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1256)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1210)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
    ... 45 more

link do github do projeto https://github.com/samuelvelter2/kemedico (coloquei o link, porque as classes são grandes demais pro fórum do Alura :P ) A versão do Spring é a 5.2.5 e a do Spring security é 5.3.1( e é a versão recomendada pra 5.2.5 do spring, é o que tá no MvnRepository)

2 respostas

O erro acontece no autowired do UsuarioDAO da SecurityConfiguration

package br.com.kemedico.conf;

import org.springframework.beans.factory.annotation.Autowired;
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.crypto.bcrypt.BCryptPasswordEncoder;

import br.com.kemedico.daos.UsuarioDAO;

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    private UsuarioDAO usuarioDao;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/cadastro/**").permitAll().antMatchers("/login/").permitAll()
                .antMatchers("/buscar/**").hasRole("USUARIO").antMatchers("/premium/beneficios").permitAll()
                .anyRequest().authenticated().and().formLogin();

    }

    @Override
    @Autowired
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(usuarioDao).passwordEncoder(new BCryptPasswordEncoder());
    }
}

e eis a UsuarioDAO:

package br.com.kemedico.daos;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;

import br.com.kemedico.model.Usuario;

@Repository
public class UsuarioDAO implements UserDetailsService {
    @PersistenceContext
    private EntityManager manager;

    @Override
    public UserDetails loadUserByUsername(String chaveAcesso) throws UsernameNotFoundException {
        List<Usuario> usuarios = manager.createQuery("select u from Usuario u where email = :chaveAcesso OR cpf = :chaveAcesso", Usuario.class).getResultList();
        if (usuarios.isEmpty()) {
            throw new UsernameNotFoundException("Usuário não encontrado");
        }
        return usuarios.get(0);
    }

}
solução!

é o seguinte, as configurações do SpringServlet precisam ser alteradas, então todas as classes que estava em getServletConfigClasses DEVEM(sério mesmo) ir para getRootConfig Classes