Vraptor3中依赖注入的问题

Vraptor3声称:


Spring Integration

VRaptor works inside Spring and uses ApplicationContext from your application once available. Then, all the Spring functionalities and modules work with VRaptor without any VRaptor configuration.

其实并非如此,有这样的问题:


当一个类同时又无参数构造函数及有参数构造函数时,使用Spring的@Autowired会得到空值,且不会抛出注入失败的异常。示例代码如下(来自JForum3里的代码):

public class Category implements Serializable {

    public  Category(){} 

    @Autowired
    public Category(CategoryRepository repository) {
        this.repository = repository;
    }

}

这段代码里,repository 一直是null。

原因是:

Vraptor3用br.com.caelum.vraptor.ioc.spring.InjectionBeanPostProcessor覆盖了Spring中注解织入的方法org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor

代码如下:

class InjectionBeanPostProcessor extends AutowiredAnnotationBeanPostProcessor {
    //  in case we are required to change the injection annotation:
    //  public InjectionBeanPostProcessor() {
    //      this.setAutowiredAnnotationType(In.class);
    //  }

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Constructor[] determineCandidateConstructors(Class beanClass, String beanName) throws BeansException {
        Constructor[] candidates = super.determineCandidateConstructors(beanClass, beanName);
        if (candidates == null) {
            Constructor constructor = checkIfThereIsOnlyOneNonDefaultConstructor(beanClass);
            if (constructor != null) {
                candidates = new Constructor[]{constructor};
            }
        }
        return candidates;
    }


@SuppressWarnings({ "rawtypes" })
private Constructor checkIfThereIsOnlyOneNonDefaultConstructor(Class beanClass) {
        Constructor[] constructors = beanClass.getDeclaredConstructors();
        if (constructors.length == 1) {
            if (constructors[0].getParameterTypes().length > 0) {
                return constructors[0];
            }
        }
        return null;
    }
}

简单粗暴的判断被注入类的构造函数数量,如果有多个构造函数,直接返回null。所以你会发现明明写了注入,也没有报错,但就是没值。



转载于:https://my.oschina.net/u/1052508/blog/147584

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值