1

In my project I have two servlets and common datasource for both servlets. First servlet is mvc, second is JAXWS. Second servlet have always null for @Autowired fields. My decision for checking this fields for null is so:

public class InRequestServiceImpl implements InRequestService {

    @Autowired
    public InRequestDao inRequestDao;// = new InRequestDaoImpl();


    public InRequestServiceImpl() {
        if (inRequestDao == null) inRequestDao = new InRequestDaoImpl();
    }

    @Override
    @Transactional
    public void insertData(InRequest doc) throws IOException {
        inRequestDao.insertData(doc);
    }
...
}

referenced question: SPRING: visibility of autowired beans in services

The question is : is there a good practice for this situation? Help to write clean code.

zond
  • 1,473
  • 1
  • 21
  • 34
  • 1
    no. normally autowired should always be there. how did you configure them? – Stultuske Nov 27 '17 at 12:39
  • I prefer constructor injection like this: `@Autowired public InRequestServiceImpl(InRequestDao inRequestDao) { this.inRequestDao = inRequestDao; }` – David Pérez Cabrera Nov 27 '17 at 12:40
  • @DavidPérezCabrera which probably would lead to the same problem, since his autowired fields are null :) – Stultuske Nov 27 '17 at 12:41
  • @Stultuske You are right, but I was thinking about the unit testing. – David Pérez Cabrera Nov 27 '17 at 12:44
  • No it isn't. `@Autowired` fields are simply never `null` if they are it means those are bean instances not managed by Spring. The fact that you mention servlets makes me think that you have classic servlets, managed by the servlet container and expect spring to magically inject dependencies into them. – M. Deinum Nov 27 '17 at 12:54
  • @M.Deinum I've added referenced question to post – zond Nov 27 '17 at 14:23
  • And why is this different.. That was a duplicate and this is as well. Spring `@Autowired` fields are simply never `null` if they are the bean isn't managed by spring or you haven't setup annotation processing (the latter is nowadays almost impossible to do the first however is quite easy to do). – M. Deinum Nov 27 '17 at 14:44

1 Answers1

1

The question is : is there a good practice for this situation?

No, there isn't. In the 90% of cases if you don't get the autowired field "initialized" then it usually means that your class is not managed by the dependency injection framework(spring in this case). I recommend you to review your spring configuration. For example: Have you annotated the service class with @Service annotation ? Besides look at here it could be help

gtosto
  • 1,381
  • 1
  • 14
  • 18