0

For some reason my Autowired is not working in my case. class MyService is used in an Controller and I always get a NullPointerException because userDao is null. I put the classes in different packages but Spring does not inject it. Also the Transaction does not work. I intentionally assign null to an attribute in holiday which causes an Exception but still User table is not rolled back. Please help me.

@Service
@Configurable
public class MyService {

    @Autowired
    UserDao userDao;

    @Autowired
    HolidayDao holidayDao;

    @Transactional(isolation=Isolation.READ_COMMITTED, propagation=Propagation.REQUIRED,readOnly=false,timeout=1000, rollbackFor=Exception.class)
    public void saveUserAndHoliday(User user, Holiday holiday)
    {
        userDao.save(user);     
        holiday.setOvertime(null);
        holidayDao.save(holiday);
    }
}

This is userDao class. I use it basically in every Controller class but there it works to be injected. Why not in this service class.

@Repository
public interface UserDao extends JpaRepository<User, Long> {

    User findByUserName(String userName);

    User findById(long id);

}
Alicia17
  • 75
  • 5
  • Show the UserDao class code – Anton Dikarev Feb 11 '20 at 09:52
  • Are you able to autowire the service class to a controller ? Also , when userDao is null , how is the code flow reaching `holiday.setOvertime(null)` – R.G Feb 11 '20 at 10:00
  • English please! – Smile Feb 11 '20 at 10:18
  • Yes in the controller it is autowired. Only userDao and holidayDao are null and are not autowired.Of course holiday.setOvertime(null) is not reached. I did this without autowired, Passing by construktor if you understand – Alicia17 Feb 11 '20 at 10:21
  • Try removing Configurable annotation from service class. To me it looks like when you annotate any class with Configurable annotation, it says that Default Autowire.NO. That means- By default none of the beans will be auto wired to your service class. Most probably you don't have Configurable annotation on your Controller and that's why your dao is not null there. – Sachin Feb 11 '20 at 10:49
  • ok thanks. Seems to work. Now I get this error No qualifying bean of type [org.springframework.transaction.PlatformTransactionManager] is defined: expected single matching bean but found 2: transactionManager,hibernateTransactionManager . I took over this project and I do not know if my colleague defined 2 TransactionManagers. I solved the problem now with @Transactional("transactionManager") – Alicia17 Feb 11 '20 at 10:59

0 Answers0