Spring 容器的配置方式有三種洋满,在實際項目中荠呐,可能會遇到混合使用的情況邓厕,也可能需要從一種方式遷移到另一種方式炫惩。
一、配置兼容
Spring 的三種配置方式混合使用蔓榄,需要兼容 XML 配置和注解配置并炮。
1. 優(yōu)先 XML 配置
在老的 Spring 項目中,常常會存在大量的 XML 配置甥郑,但并不影響我們使用注解配置的新特性逃魄。
XML 配置中使用注解配置
配置文件中使用 context:component-scan
來配置掃描的包路徑。
該路徑下的類就支持 @Configuration
澜搅、@Component
和 @Autowired
等注解伍俘。
<beans>
<context:component-scan base-package="cn.codeartist.spring.bean.mix"/>
</beans>
XML 配置中使用 Java 配置
掃描的包路徑下使用 @Configuration
定義配置類邪锌,在配置類中使用 @Bean
注冊 Bean。
2. 優(yōu)先注解配置
老的 Spring 項目在遷移的過程中癌瘾,可能需要在使用注解和 Java 的配置中川无,使用 XML 配置直秆。
注解配置中使用 XML 配置
在配置類上使用 @ImportResource
來導入 XML 配置文件。
@Configuration
@ImportResource("classpath:bean.xml")
public class AppConfig {
}
classpath:bean.xml
表示基于 classpath 路徑的資源文件眉孩。
注解配置中使用 Java 配置
直接在配置類中使用 @Bean
注冊 Bean笙隙。
@Configuration
@ComponentScan("cn.codeartist.spring.bean.mix")
public class AppConfig {
@Bean
public BeanExample beanExample() {
return new BeanExample();
}
}
或者在掃描的包路徑下使用 @Configuration
注解定義配置類暗挑。
二膛薛、遷移方案
基于 XML 配置的容器使用 ClassPathXmlApplicationContext
或 FileSystemXmlApplicationContext
實例化迷捧。
基于注解配置的容器使用 AnnotationConfigApplicationContext
實例化。
// XML
public static void main(String[] args) {
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("bean.xml");
BeanExample beanExample = (BeanExample) applicationContext.getBean("beanExample");
}
// 注解
public static void main(String[] args) {
ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(AppConfig.class);
BeanExample beanExample = (BeanExample) applicationContext.getBean("beanExample");
}
1. XML 配置至注解配置
配置文件中添加 context:component-scan
指定掃描的包路徑幸乒。
2. XML 配置至 Java 配置
XML 配置中的<beans>
和<bean>
標簽懦底,等效于 Java 配置中的@Configuration
和@Bean
配置。
<beans>
<bean id="beanExample" class="cn.codeartist.spring.bean.mix.BeanExample"/>
</beans>
等效于:
@Configuration
public class AppConfig {
@Bean
public BeanExample beanExample() {
return new BeanExample();
}
}
屬性對照
XML 配置和注解配置對應屬性遷移逝变。
XML配置 | 注解配置 |
---|---|
<context:component-scan> |
@ComponentScan |
<bean> 的 id 屬性 |
@Bean 的 value 或 name 屬性 |
<bean> 的 scope 屬性 |
@Scope |
<bean> 的 depends-on 屬性 |
@DependsOn |
<bean> 的 lazy-init 屬性 |
@Lazy |
<bean> 的 primary 屬性 |
@Primary |
<bean> 的 init-method 屬性 |
@Bean 的 initMethod 屬性 |
<bean> 的 destroy-method 屬性 |
@Bean 的 destroyMethod 屬性 |
三、附錄
1. 配置屬性
屬性 | 描述 |
---|---|
context:component-scan |
在基于 XML 配置容器中奋构,指定掃描包路徑 |
2. 常用注解
注解 | 描述 |
---|---|
@Configuration |
指定 Bean 的配置類 |
@ComponentScan |
(默認為類所在的包)指定包路徑壳影,該包下的類由容器管理 |
@Component |
指定該類由 Spring 容器管理 |
@ImportResource |
注解配置中導入 XML 配置文件 |
3. 示例代碼
Gitee 倉庫:https://gitee.com/code_artist/spring
項目模塊:spring-ioc
示例路徑:cn.codeartist.spring.bean.mix
最新文章關注 CodeArtist 碼匠公眾號。