@Configuration介绍

Spring3.0之前要使用Spring必须要有一个xml配置文件,这也是Spring的核心文件,而Spring3.0之后可以不要配置文件了,通过注解@Configuration完全搞定。

@Configuration即用来代替Spring配置文件的,它就是一个@Component组件,接收一个value值也就是bean的名字,value可以不填。

@Configuration使用

下面是一个使用实例,创建了一个userService和accountService的实例,accountService实例引用userService实例。

@Configuration
@ComponentScan(basePackages = { "com.test.web" })
@Import(UserConfg.class)
@ImportResource(locations = {"classpath:config/spring-beans.xml"})
public class MainConfg {

@Bean(name = "userService", initMethod = "init", destroyMethod = "destroy")
@Scope("singleton")
public UserService userService() {

    return new UserService();

    }

    @Bean
    public AccountService accountService(UserService userService) {
        AccountService as = new AccountService();
        as.setUserService(userService);
        return as;
    }

}

注解说明

@Configuration:代表这个类是一个配置类。

@ComponentScan:用来扫描指定包下面的注解类。

@Import:用来导入其他的@Configuration配置类。

@ImportResource:用来导入xml配置文件,比如某些配置一定要xml配置。

@Bean:用来定义一个bean,可以指定初始、销毁方法,及bean范围等。

这些注解都在spring-context包下,还有其他注解用来解放xml形式的配置,大量xml配置可java配置化,只要定义好,Spring会自动扫描包下面的@Configuration注解的配置文件类来装配。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注