Создание аспекта Spring @Controller с окончательными полями @Autowired в конструкторе

У меня есть настройка аспекта

@Aspect
@Component
public class JsonAspect {

    @Around("execution(public au.com.mycompany.common.json.response.JsonResponse *(..)) " +
            "&& @annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public final Object beforeMethod(final ProceedingJoinPoint joinPoint) throws JsonException {
        try {
            System.out.println("before...................");
            System.out.println(joinPoint.getSignature().getName());
            return joinPoint.proceed();
        } catch (Throwable t) {
            throw new JsonException(t);
        }

    }
}

Я это должен применить к классу @Controller со следующим методом

@RequestMapping(value = "/validate",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public final JsonResponse<JsonValidationResponse> validateViaJson(...

Проблема в том, что я внедряю зависимости через @Autowired

private final ClientService clientService;
private final VehicleService vehicleService;

@Autowired
public QuoteControllerImpl(
        final ClientService clientService,
        final VehicleService vehicleService,
        ) {
    this.clientService = clientService;
    this.vehicleService = vehicleService;
}

Когда я пытаюсь проксировать этот класс, он жалуется, что нет конструктора по умолчанию. поэтому я решил создать интерфейс для класса, но теперь я получаю следующую ошибку в несвязанном методе в том же классе.

java.lang.IllegalArgumentException: объект не является экземпляром объявляющего класса

Вышеупомянутая ошибка относится к методу, который находится в том же классе, но не является частью аспекта. Если удалить аспектную точку, она работает (событие с новым интерфейсом). Таким образом, кажется, что прокси-сервер Aspectj каким-то образом вызывает проблему.

Кто-нибудь знает, почему?

ОБНОВИТЬ

@nicholas.hauschild Я попробовал ваше решение, но теперь я получаю исключение NullPointer Exception при инициализации своей карты.

@ModelAttribute
public final void initialiseModel(final ModelMap map, @PathVariable("status") final String status) {
        map.addAttribute(CLIENTS, clientService.getClients());

clientService имеет значение null.


person jax    schedule 26.07.2013    source источник


Ответы (1)


Я не большой поклонник этого решения, но если вы создадите конструктор по умолчанию вместе с @Autowired, Spring все равно будет использовать @Autowiredone.

private final ClientService clientService;
private final VehicleService vehicleService;

@Autowired
public QuoteControllerImpl(
        final ClientService clientService,
        final VehicleService vehicleService,
        ) {
    this.clientService = clientService;
    this.vehicleService = vehicleService;
}

public QuoteControllerImpl() {
    //Spring won't use me...
    this.clientService = null;
    this.vehicleService = null;
}
person nicholas.hauschild    schedule 26.07.2013
comment
Я пробовал это, но теперь я получаю исключение NullPointer на моей ModelMap (см. обновленный вопрос) - person jax; 26.07.2013