AspectJ: Autowired fields are null in Initbinder
Asked Answered
A

1

6

I just implemented AspectJ like described here: https://mcmap.net/q/1064135/-autowiring-in-spring-bean-component-created-with-new-keyword

This solution works fine, until I noticed that my @Autowired fields are null within @InitBinder. The fields are only null within the @InitBinder.

@Controller
public class EmployeeController {
    @Autowired private GenericDaoImpl<Role, Integer> roleDao;
    @Autowired private GenericDaoImpl<Employee, Integer> employeeDao;
    @Autowired private EmployeeValidator employeeValidator;

    @InitBinder
    private void initBinder(WebDataBinder binder) {
        // autowired fields are null 
        binder.setValidator(employeeValidator);
        binder.registerCustomEditor(Set.class, "roles", new CustomCollectionEditor(Set.class) {
            protected Object convertElement(Object element) {
                if (element != null) {
                    Integer id = new Integer((String) element);
                    Role role = roleDao.findById(id);
                    return role;
                }
                return null;
            }
        });
    }

    @PreAuthorize("hasRole('MASTERDATA_VIEW')")
    @RequestMapping(value = { "/employees" }, method = RequestMethod.GET)
    public ModelAndView showEmployeeList() {
        // dao not null
        List<Employee> employees = employeeDao.findAll();
            ...
    }

I cannot comprehend why they are sometimes null and somethimes not.(within the same class)

Avilla answered 7/2, 2014 at 11:28 Comment(0)
A
15

@Initbinder must be declared as public.

Avilla answered 7/2, 2014 at 12:2 Comment(2)
Thank you, one of the methods in my controller was marked as private. Couldn't figure out why all the rest were working and that one wasn't.Trenchant
Worked with protected too. Thanks.Trinee

© 2022 - 2024 — McMap. All rights reserved.