@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定义的源。

原文地址:https://www.cnblogs.com/soundcode/p/6478004.html