@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();
    }

}
标签: spring, @Bean
### 作用及使用示例 #### @Configuration 注解 @Configuration 是 Spring 框架中用于定义配置类的注解。这些配置类可以替代传统的 XML 配置文件,提供了一种更加灵活强大的方式来配置 Spring 容器[^3]。一个被 @Configuration 注解标记的类表明该类内部包含了一个或多个通过 @Bean 注解定义的方法,这些方法将返回需要由 Spring 容器管理的对象(即 beans)。 **使用示例:** ```java @Configuration public class AppConfig { // @Bean 方法将会在这里定义 } ``` #### @Bean 注解 @Bean 是 Spring 框架中的另一个重要注解,它允许开发者在配置类中创建配置对象,这些对象随后会被 Spring 容器管理[^1]。通常情况下,@Bean 注解会与 @Configuration 注解一起使用,在配置类中定义一个或多个 bean。 **使用示例:** ```java @Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } } ``` 在这个例子中,`myService()` 方法返回一个 `MyService` 接口的实现类 `MyServiceImpl` 的实例。这个实例将会被 Spring 容器管理,并且可以在应用程序中的其他地方通过依赖注入获取到。 #### 生命周期管理 当使用 @Configuration @Bean 注解时,Spring 会处理这些 bean 的生命周期,包括初始化、使用以及销毁阶段[^2]。例如,可以通过实现 InitializingBean DisposableBean 接口或者自定义 init destroy 方法来控制 bean 的生命周期。 **自定义初始化销毁方法示例:** ```java @Configuration public class AppConfig { @Bean(initMethod = "init", destroyMethod = "cleanup") public MyService myService() { return new MyServiceImpl(); } } // 在 MyServiceImpl 中 public class MyServiceImpl implements MyService { public void init() { // 初始化逻辑 } public void cleanup() { // 清理逻辑 } } ``` #### 相互依赖 在一个 @Configuration 类中,可能有多个 @Bean 方法相互依赖的情况。在这种情况下,可以通过直接调用同一个配置类中的其他 @Bean 方法来满足这种依赖关系。 **相互依赖示例:** ```java @Configuration public class AppConfig { @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder().build(); } @Bean public JdbcTemplate jdbcTemplate() { return new JdbcTemplate(dataSource()); // 直接调用 dataSource() 方法 } } ``` 这里展示了如何在一个 @Bean 方法中直接调用另一个 @Bean 方法以建立 bean 之间的依赖关系。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值