WildFly 10 + Spring Security + JSF + CDI does not inject dependency

1

I'm trying to implement CDI in a WEB project that I have where I use WildFly10 with Spring Security (custom login) and JSF and I'm not able to inject dependencies.

In the Example below, the UserDao when used

  

Caused by: java.lang.NullPointerException at   br.com.transportesalvorada.security.configall.ServicoDetalhamentoUsuario.loadUserByUsername (ServicoDetalhamentoUsuario.java:39)

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.enterprise.context.Dependent;
import javax.inject.Inject;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.Service;

import br.com.transportesalvorada.security.bean.Usuario;
import br.com.transportesalvorada.security.dao.UsuarioDao;


@Service("servicoDetalhamentoUsuario")
public class ServicoDetalhamentoUsuario implements UserDetailsService, Serializable {

    private static final long serialVersionUID = 1L;

    @Inject 
    private UsuarioDao usuarioDao;


    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

        System.out.println("\n---[ServicoDetalhamentoUsuario]--------------------------");
        System.out.println("\n email :"+ email);

        //usuarioDao = new UsuarioDao();
        Usuario usuario = usuarioDao.consulta(email);

        if(usuario != null && usuario.getEmail() != null){
            System.out.println("\n usuario :"+usuario.getEmail());
            System.out.println("\n grupos  :"+usuario.getGrupos().size());
            return new UsuarioSistema(usuario, getGrupo(usuario));
        }
        return  null;



    }

    private Collection<? extends GrantedAuthority> getGrupo(Usuario usuario) {
        List<SimpleGrantedAuthority> grupos = new ArrayList<SimpleGrantedAuthority>();
        usuario.getGrupos().forEach(g->{
            grupos.add(new SimpleGrantedAuthority(g.getNome().toUpperCase()));
        });
        return grupos;
    }

}


import java.io.Serializable;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import br.com.transportesalvorada.modeldao.dao.JpaUtil;
import br.com.transportesalvorada.security.bean.Usuario;


public class UsuarioDao implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public Usuario consulta(String email) {

        System.out.println("\n -------- Entrou no Usuario.consulta - antes do EM");

        EntityManager entityManager = new JpaUtil().geraEM();
        Usuario usuario = new Usuario();
        try{
            TypedQuery<Usuario> query = entityManager.createQuery("select u from Usuario u where u.email = :pEmail",Usuario.class);
            query.setParameter("pEmail", email);
            usuario = query.getSingleResult();
            usuario.getGrupos().size();
            return usuario;

        } catch (Exception e) {
            System.out.printf("\n Erro %s \n" , e);
        }   
        return usuario;
    }


}

My Project Structure

My Pom.xml

     <dependencies>
        <!--  Testes JUnit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- CDI teste --> 
        <dependency>
            <groupId>org.jglue.cdi-unit</groupId>
            <artifactId>cdi-unit</artifactId>
            <version>3.1.2</version>
            <exclusions>
                <exclusion>
                    <artifactId>dom4j</artifactId>
                    <groupId>dom4j</groupId>
                </exclusion>
            </exclusions>
            <scope>test</scope>
        </dependency>

        <!--  Configuracao de Persistencia 
        <dependency>
            <groupId>${project.groupId}</groupId> 
            <artifactId>perolawebmodelsecurit</artifactId> 
            <version>1.0.0</version> 
        </dependency> 
        <dependency>
            <groupId>${project.groupId}</groupId> 
            <artifactId>perolawebmodeldao</artifactId> 
            <version>1.0.0</version> 
        </dependency>
        -->

        <!--  Spring Security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>

        <dependency>  
            <groupId>org.primefaces</groupId>  
            <artifactId>primefaces</artifactId>  
            <version>6.0</version>  
        </dependency>
        <dependency>  
            <groupId>org.primefaces.themes</groupId>  
            <artifactId>bootstrap</artifactId>  
            <version>1.0.10</version>  
        </dependency>

        <!--  Quando for WildFly -->
        <dependency>
            <groupId>org.wildfly</groupId>
            <artifactId>wildfly-jsf</artifactId>
            <version>10.0.0.Final</version>
        </dependency>
        <!--  CDI -->
        <dependency>
           <groupId>javax.enterprise</groupId>
           <artifactId>cdi-api</artifactId>
           <version>1.2</version>
        </dependency>

        <!--  DB-Postgresql -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.4-1200-jdbc41</version>
        </dependency>
        <!--  JPA-Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.0.Final</version>
            <exclusions>
                <exclusion>
                    <artifactId>dom4j</artifactId>
                    <groupId>dom4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--  Hibernate Validator -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.2.4.Final</version>
            <scope>compile</scope>
        </dependency>
  </dependencies>
    
asked by anonymous 22.06.2016 / 22:50

1 answer

2

You are using Spring Security and CDI, both have a different dependency injection context as soon as the CDI-managed DAO will not be available for the context of Spring Security. In a project to work around this problem I had to use the following class to return the beans that are in the CDI injection context for Spring Security to use properly.

public class CDIServiceLocator {

    private static BeanManager getBeanManager() {
        try {
            InitialContext initialContext = new InitialContext();
            return (BeanManager) initialContext.lookup("java:comp/env/BeanManager");
        } catch (NamingException ex) {
            throw new RuntimeException("Bean não encontrado no JNDI");
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clazz) {
        BeanManager bm = getBeanManager();
        Set<Bean<?>> beans = (Set<Bean<?>>) bm.getBeans(clazz);

        if (beans == null || beans.isEmpty()) {
            return null;
        }

        Bean<T> bean = (Bean<T>) beans.iterator().next();

        CreationalContext<T> ctx = bm.createCreationalContext(bean);
        T o = (T) bm.getReference(bean, clazz, ctx);
        return o;
    }

}

Within the method that will use DAO, place the following call:

MeuDAO meuDAO = CDIServiceLocator.getBean(MeuDAO.class);

Udate

Where java:comp/env/BeanManager is replaced with java:comp/BeanManager

I did a test using Wildfly 10 and it worked correctly

    
23.06.2016 / 15:42