@Configuration 和 @Bean


1. @Bean:

1.1 定義

從定義可以看出,@Bean只能用於注解方法和注解的定義。

 
        
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
 
        

1.2 spring文檔中對 @Bean的說明

The @Bean annotation is used to indicate that a method instantiates, configures and initializes a new object to be managed by the Spring IoC container.

For those familiar with Spring’s <beans/> XML configuration the @Bean annotation plays the same role as the <bean/>element. 

用@Bean注解的方法:會實例化、配置並初始化一個新的對象,這個對象會由spring IoC 容器管理。

實例:

復制代碼
@Configuration
public class AppConfig {

    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }

}
復制代碼

相當於在 XML 文件中配置

<beans>
    <bean id="myService" class="com.acme.services.MyServiceImpl"/>
</beans>

 

1.3 生成對象的名字:默認情況下用@Bean注解的方法名作為對象的名字。但是可以用 name屬性定義對象的名字,而且還可以使用name為對象起多個名字。

復制代碼
@Configuration
public class AppConfig {

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

}
復制代碼

 

復制代碼
@Configuration
public class AppConfig {

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

}
復制代碼

 

1.4 @Bean 一般和 @Component或者@Configuration 一起使用。

@Component和@Configuration不同之處

(1)This method of declaring inter-bean dependencies only works when the @Bean method is declared within a @Configurationclass. You cannot declare inter-bean dependencies using plain @Component classes.

在 @Component 注解的類中不能定義 類內依賴的@Bean注解的方法。@Configuration可以。

復制代碼
@Configuration
public class AppConfig {

    @Bean
    public Foo foo() {
        return new Foo(bar());
    }

    @Bean
    public Bar bar() {
        return new Bar();
    }

}
復制代碼

 

2. @Configuration:

2.1 定義

從定義看,用於注解類、接口、枚舉、注解的定義。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)

 2.2 spring 文檔說明

@Configuration is a class-level annotation indicating that an object is a source of bean definitions. @Configuration classes declare beans via public @Bean annotated methods.

@Configuration用於類,表明這個類是beans定義的源。


免責聲明!

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



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