在构造函数中使用@Autowired最终字段在spring @Controller上创建方面

时间:2013-07-26 00:26:02

标签: spring spring-mvc aspectj spring-aop

我有一个方面设置

@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);
        }

    }
}

我应该使用以下方法将<{1}}类应用于

@Controller

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

注入依赖项
@Autowired

当我尝试代理这个类时,它抱怨没有默认的构造函数。所以我决定为该类创建一个接口,但现在我在同一个类中的一个不相关的方法上得到以下错误。

  

java.lang.IllegalArgumentException:object不是。的实例   宣布课程

上述错误适用于同一类但不属于aspectj切入点的方法。如果删除aspectj切入点它可以工作(具有新接口的事件)。所以似乎aspectj代理以某种方式引起了问题。

任何人都知道为什么?

更新

@ nicholas.hauschild我尝试了你的解决方案,但现在我在初始化地图时遇到了NullPointer异常。

private final ClientService clientService;
private final VehicleService vehicleService;

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

clientService 为空。

1 个答案:

答案 0 :(得分:0)

我不是这个解决方案的忠实粉丝,但是如果您创建默认构造函数以及@Autowired,那么Spring将使用@Autowired一个。

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;
}