---
title: "AnnotationFormatError when using Spring 3.0 & JavaConfig"
author: "hypgr"
date: "2011-02-25T10:52:28Z"
tags: []
categories: ["企业架构"]
slug: "annotationformaterror-when-using-spring-3-0-javaconfig"
draft: false
lastmod: "2011-02-25T10:52:28Z"
id: 927657
url: "https://hypgr.iteye.com/blog/927657"
---

[Spring 3.0M3]() 及其以后的版本包含了JavaConfig 项目提供的大部分功能. 如果你的程序遭遇如下异常:

Exception in thread "main" java.lang.annotation.AnnotationFormatError: Invalid default: public abstract org.springframework.beans.factory.annotation.Autowire

  org.springframework.config.java.annotation.Configuration.defaultAutowire()

 

    这很可能是因为你在Classpath 中添加了JavaConfig 项目release 出来的包( 比如[]() [org.springframework.config.java-1.0.0.M4.jar]() ), 而在程序中使用JavaConfigApplicationContext 类。查看org.springframework.config.java-1.0.0.M4.jar 包的source code, 你会发现org.springframework.config.java.annotation.Configuration 类的defaultAutowire 的定义如下:

Autowire defaultAutowire() default []()[Autowire]() .INHERITED;

    而查看org.springframework.beans.factory.annotation.Autowire 枚举类，你会发现INHERITED 根本就没有定义( 只有NO, BY\_NAME 和BY\_TYPE 三种) 。这就难怪会报错了。

 

    事实上，由于Spring 3.0M3 及其以后的版本包含了JavaConfig 项目提供的大部分功能，你无需为应用再添加JavaConfig 的包。@Configuration, @Bean 等都已经被整合到了org.springframework.context.annotation 下, 从文件来看就是org.springframework.context.jar 包。下图展示了一个可运行项目的Classpath 配置:

![](http://www.blogjava.net/images/blogjava_net/brian/jconfig.png)

   由于没有了JavaConfig 项目release 的包, JavaConfigApplicationContext 类也就无法找到了，你需要将它替换成org.springframework.context.annotation.AnnotationConfigApplicationContext, 例如:

**public** **static** **void** main(String\[] args) {

ApplicationContext context = **new**

AnnotationConfigApplicationContext(ApplicationConfig.**class** );

String x = context.getBean("x", String.**class** );

System.*out* .println("Got x: " + x);

}