[java] view plaincopy
- // 假设存在如下的 @Configuration 类:
- package bookstore.config;
- import bookstore.dao.*;
- @Configuration
- public class MyConfig{
- @Bean
- public UserDao userDao(){
- return new UserDaoImpl();
- }
- }
此时,只需要在Spring XML配置文件中做如下声明即可:
[xhtml] view plaincopy
-
- ……
-
-
由于启用了针对注解的 Bean 后处理器,因此在 ApplicationContext 解析到 MyConfig 类时,会发现该类标注了 @Configuration 注解,
随后便会处理该类中标注 @Bean 的方法,将这些方法的返回值注册为容器总的 Bean。
对于以上的方式,如果存在多个标注了 @Configuration 的类,则需要在 XML 文件中逐一列出。另一种方式是使用前面提到的自动扫描功能
,配置如下:
[xhtml] view plaincopy-
如此,Spring 将扫描所有 demo.config 包及其子包中的类,识别所有标记了 @Component、@Controller、@Service、@Repository
注解的类,由于 @Configuration 注解本身也用 @Component 标注了,Spring 将能够识别出 @Configuration 标注类并正确解析之。
对于以注解为中心的配置方式,只需使用 @ImportResource 注解引入存在的 XML 即可,如下所示:
[java] view plaincopy- @Configuration
- @ImportResource(“classpath:/bookstore/config/spring-beans.xml”)
- public class MyConfig{
- ……
- }
- // 容器的初始化过程和纯粹的以配置为中心的方式一致:
- AnnotationConfigApplicationContext ctx =
- new AnnotationConfigApplicationContext(MyConfig.class);
- ……
-