将XML迁移到
@Configuration
@Configuration只需几个步骤即可将xml迁移到:
- 创建一个带
@Configuration
注释的类:
@Configurationpublic class MyApplicationContext {}- 为每个
<bean>
标签创建一个方法,其注释为@Bean
:
@Configurationpublic class MyApplicationContext { @Bean(name = "someBean") public SomeClass getSomeClass() { return new SomeClassImpl(someInterestingProperty); // We still need to inject someInterestingProperty } @Bean(name = "anotherBean") public AnotherClass getAnotherClass() { return new AnotherClassImpl(getSomeClass(), beanFromSomewhereElse); // We still need to inject beanFromSomewhereElse }}- 为了导入,
beanFromSomewhereElse
我们需要导入它的定义。可以用XML定义它,我们将使用@importResource
:
@importResource("another-application-context.xml")@Configurationpublic class MyApplicationContext { ... }如果bean是在另一个
@Configuration类中定义的,则可以使用
@import注释:
@import(OtherConfiguration.class)@Configurationpublic class MyApplicationContext { ...}- 导入其他XML或
@Configuration
类之后,可以通过在@Configuration
类中声明私有成员来使用它们在上下文中声明的bean ,如下所示:
@Autowired@Qualifier(value = "beanFromSomewhereElse")private final StrangeBean beanFromSomewhereElse;
或者用它直接作为在其中定义了取决于该豆的方法参数beanFromSomewhereElse使用@Qualifier如下:
@Bean(name = "anotherBean")public AnotherClass getAnotherClass(@Qualifier (value = "beanFromSomewhereElse") final StrangeBean beanFromSomewhereElse) { return new AnotherClassImpl(getSomeClass(), beanFromSomewhereElse);}- 导入属性与从另一个xml或
@Configuration
类导入bean非常相似。除了使用,@Qualifier
我们将使用@Value
以下属性:
@Autowired@Value("${some.interesting.property}")private final String someInterestingProperty;这也可以与SpEL表达式一起使用。
- 为了允许spring将此类视为bean容器,我们需要通过将以下标记放在上下文中在主xml中对其进行标记:
<context:annotation-config/>
现在,你可以导入
@Configuration与创建简单bean完全相同的类:
<bean />
有一些方法可以完全避免使用Spring XML,但是它们不在此答案的范围内。你可以在我基于其答案的博客文章中找到这些选项之一。
使用此方法的优缺点
基本上,由于一些优势,我发现这种声明bean的方法比使用XML更舒适。
Typos - @Configuration
类已编译,拼写错误将不允许编译Fail fast (compile time)
-如果你忘记注入Bean,则会在编译时失败,而不是像XML那样在运行时失败Easier to navigate in IDE
-在bean的构造函数之间了解依赖关系树。- 可以轻松调试配置启动
正如我所看到的那样,缺点并不多,但我可以想到一些缺点:
- 滥用 -代码比XML更容易滥用
- 使用XML,你可以基于在编译时不可用但在运行时提供的类定义依赖项。使用
@Configuration
类时,必须在编译时提供可用的类。通常这不是问题,但是在某些情况下可能是这样。
底线:在你的应用程序上下文中结合XML@Configuration
和注释是完全可以的。Spring并不关心使用bean声明的方法。



