Spring MVC - Multiple Builders

Asked

Viewed 183 times

0

I’m having a problem where a Framework I’m using needs a default constructor, this one calling my Service class:

@Service
public class FuncionarioService {

private FuncionarioDAO dao;


    public FuncionarioService(){        
    }   

    @Autowired
    public FuncionarioService(FuncionarioDAO dao) {
        this.dao = dao;
    }   

When calling the method below, the variable "dao" comes "null". When using another path that does not use the Framework, everything is normal, the variable is different from "null".

public List<Funcionario> obterFuncionarios(Hierarquia hierarquia){
        List<Funcionario> listaFuncionarios = new ArrayList<Funcionario>();
        listaFuncionarios = dao.obterFuncionarios(hierarquia);
        return listaFuncionarios;
    }

1 answer

0

You are trying to make the instance of a Spring service object, try using @Autowired to inject this object and make sure it works.

When you use a @Service, you are creating a service with inversion of control and can be injected. The moment you try to add or instantiate an object, problems may occur as you theoretically break the control inversion chain.

  • Thiago, I’ve tried adding @Autowired to the default constructor, but it needs at least 1 parameter, if not the error.

  • Oops, sorry, you don’t need to add it as a constructor attribute. Try using it like this: "@Autowired" private Dao dao; E you can use the dao object freely as long as it is a "@Service" too.

  • On my DAO I use the @Repository notation =\

  • Perfect, that’s right. It works the same way, you must be using Spring Data.

  • It didn’t work, still this like Null.

  • Aren’t you injecting it into the right constructor? You’re taking the instantiated "dao" and using it directly, correct?

  • In the mode I’m using, I’m injecting it into the constructor. But for a new situation, it doesn’t recognize it. @Autowired public Functionservice(Functionat dao) { this.dao = dao; }

  • Abandon this injection in the constructor, if you are already injecting it in your class you already have it available for use, use as previously @Autowired private Dao dao; And use it normally.

  • It didn’t work bro, it keeps going like null. @Autowired private Functiondao;

  • If your class is correct as @repositoy should work. You can update the post with the classes so I can understand how DAO is?

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.