spring @Bean注解的使用


@Bean 的用法

@Bean是一個方法級別上的注解,主要用在@Configuration注解的類里,也可以用在@Component注解的類里。添加的bean的id為方法名

定義bean

下面是@Configuration里的一個例子

@Configuration
public class AppConfig {

    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }

}

這個配置就等同於之前在xml里的配置

<beans>
    <bean id="transferService" class="com.acme.TransferServiceImpl"/>
</beans>

bean的依賴

@bean 也可以依賴其他任意數量的bean,如果TransferService 依賴 AccountRepository,我們可以通過方法參數實現這個依賴

@Configuration
public class AppConfig {

    @Bean
    public TransferService transferService(AccountRepository accountRepository) {
        return new TransferServiceImpl(accountRepository);
    }

}

接受生命周期的回調

任何使用@Bean定義的bean,也可以執行生命周期的回調函數,類似@PostConstruct and @PreDestroy的方法。用法如下

public class Foo {
    public void init() {
        // initialization logic
    }
}

public class Bar {
    public void cleanup() {
        // destruction logic
    }
}

@Configuration
public class AppConfig {

    @Bean(initMethod = "init")
    public Foo foo() {
        return new Foo();
    }

    @Bean(destroyMethod = "cleanup")
    public Bar bar() {
        return new Bar();
    }

}

默認使用javaConfig配置的bean,如果存在close或者shutdown方法,則在bean銷毀時會自動執行該方法,如果你不想執行該方法,則添加@Bean(destroyMethod="")來防止出發銷毀方法

指定bean的scope

使用@Scope注解

你能夠使用@Scope注解來指定使用@Bean定義的bean

@Configuration
public class MyConfiguration {

    @Bean
    @Scope("prototype")
    public Encryptor encryptor() {
        // ...
    }

}

@Scope and scoped-proxy

spring提供了scope的代理,可以設置@Scope的屬性proxyMode來指定,默認是ScopedProxyMode.NO, 你可以指定為默認是ScopedProxyMode.INTERFACES或者默認是ScopedProxyMode.TARGET_CLASS。
以下是一個demo,好像用到了(沒看懂這塊)

// an HTTP Session-scoped bean exposed as a proxy
@Bean
@SessionScope
public UserPreferences userPreferences() {
    return new UserPreferences();
}

@Bean
public Service userService() {
    UserService service = new SimpleUserService();
    // a reference to the proxied userPreferences bean
    service.setUserPreferences(userPreferences());
    return service;
}

自定義bean的命名

默認情況下bean的名稱和方法名稱相同,你也可以使用name屬性來指定

@Configuration
public class AppConfig {

    @Bean(name = "myFoo")
    public Foo foo() {
        return new Foo();
    }

}

bean的別名

bean的命名支持別名,使用方法如下

@Configuration
public class AppConfig {

    @Bean(name = { "dataSource", "subsystemA-dataSource", "subsystemB-dataSource" })
    public DataSource dataSource() {
        // instantiate, configure and return DataSource bean...
    }

}

bean的描述

有時候提供bean的詳細信息也是很有用的,bean的描述可以使用 @Description來提供

@Configuration
public class AppConfig {

    @Bean
    @Description("Provides a basic example of a bean")
    public Foo foo() {
        return new Foo();
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM