【SpringBoot篇】详解Bean的管理(获取bean,bean的作用域,第三方bean)
    		       		warning:
    		            这篇文章距离上次修改已过427天,其中的内容可能已经有所变动。
    		        
        		                
                
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
 
@Configuration
public class BeanConfig {
 
    // 使用@Bean注解定义一个单例bean
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
 
    // 使用@Bean注解定义一个原型bean(每次请求都会创建新的bean实例)
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public MyPrototypeBean myPrototypeBean() {
        return new MyPrototypeBean();
    }
 
    // 使用@Bean注解定义第三方库中的bean
    @Bean
    public ThirdPartyBean thirdPartyBean() {
        return new ThirdPartyBean();
    }
}
 
// 假设MyBean, MyPrototypeBean, ThirdPartyBean是已定义的类
class MyBean {
    // ...
}
 
class MyPrototypeBean {
    // ...
}
 
class ThirdPartyBean {
    // ...
}这个代码示例展示了如何在Spring Boot项目中使用@Configuration类来定义和配置beans。其中,@Bean注解用于声明一个方法实例化、配置和初始化一个新对象,这个对象加入到Spring容器中。@Scope注解用于指定bean的作用域,例如原型作用域(prototype scope),这样每次请求都会创建一个新的bean实例。第三方库中的bean可以通过@Bean注解来声明并使用。
评论已关闭