Vraptor3中依赖注入的问题

Vraptor3声称: java


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

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


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

public class Category implements Serializable {

    public  Category(){} 

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

}

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

缘由是: 函数

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

代码以下: this

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。因此你会发现明明写了注入,也没有报错,但就是没值。
相关文章
相关标签/搜索