@Bean通过实例工厂实例化Bean具体代码
时间: 2023-10-15 09:08:22 浏览: 92
回答: @Bean通过实例工厂实例化Bean的具体代码如下所示:
```java
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBeanFactory().createMyBean();
}
}
public class MyBeanFactory {
public MyBean createMyBean() {
return new MyBean();
}
}
public class MyBean {
public MyBean() {
System.out.println("MyBean Initializing");
}
}
```
在上述代码中,通过创建一个名为MyBeanFactory的实例工厂类,在工厂类中定义了createMyBean()方法用于实例化MyBean对象。在AppConfig配置类中,通过@Bean注解将myBean()方法标记为需要交由Spring进行管理的bean。当通过ApplicationContext获取bean时,Spring会调用MyBeanFactory的createMyBean()方法实例化MyBean对象,并将其纳入IOC容器中供其他组件使用。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [详细讲解Spring中的@Bean注解](https://blog.csdn.net/weixin_36380516/article/details/119194065)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文