深入Spring源码专题(10)

173 阅读2分钟

这是我参与2022首次更文挑战的第16天,活动详情查看2022首次更文挑战

深入Spring源码专题(10)

使用Java配置

将app-context-xml.xml替换为配置类,而无须修改标识正在创建的bean类型的类。当应用程序所需要的bean类型是不能修改的第三方库时,采用这种做法。配置类使用@Configuration注解,并包含用@Bean注解的方法。这些方法由SpringIoC容器直接调用来实例化Bean,Bean名称与用于创建它的方法的名称相同。

一个配置类如下所示:

@Configuration
public class BeanConfiguration{
    @Bean
    public MessageProvider provider(){
        return new MessageProvider();
    }
    
    @Bean
    public MessageRenderer renderer(){
        MessageRenderer renderer = new StandardOutMessageRenderer();
        renderer.setMessageProvider(provider());
        return renderer;
    }
}

要从这类中读取配置信息,还需要一个不同的ApplicationContext实现。

public class BeanSpringAnnotated{
	public static void main(String... args){
	ApplicationContext ctx = new AnnotationConfigApplicaitonContext(BeanConfiguration.class);
	MessageRenderer messageRenderer = ctx.getBean("renderer",MessageRenderer.class);
	messageRenderer.render();
	}
}

实例化的是AnnotationConfigApplicationContext而不是DefaultListableBeanFactory的一个实例,AnnotationConfigApplicationContext类实现了ApplicationContext接口,并且能够根据BeanConfiguration类定义的配置信息启动Spring的ApplicationContext。

使用配置类读取带注解的bean定义,在这种情况下,因为bean的定义配置是bean类的一部分,所以类将不再需要任何@Bean注解的方法,为了能够在Java类中查找Bean定义,必须启动组件扫描,可使用与<context:component-scanning .../>元素等效的注解来注解配置类,从而完成启动。注解为ComponentScanning,并具有与XML类似元素相同的参数。

@ComponentScan(basePackages = "{cm.ozx.annotation}")
@Configuration
public class BeanConfiguration{}

使用AnnotationConfigApplicationConetxt启动Spring环境的代码也可以在这个类找那个使用,无须进行额外的修改。

在现实的生产应用程序中,代码可能使用旧版本的Spring开发,或者需要使用XML和配置类。XML和Java配置可以多种方式混合使用。配置类使用@ImportResource从一个或多个XML文件中导入Bean定义,在这种情况下使用AnnotationConfigApplicaitonContext完成相同的启动过程。

@ImportResource(locations = "classpath:spring/app-context-xml.xml")
@Configuration
public class BeanConfiguration{}