-
Notifications
You must be signed in to change notification settings - Fork 17
IOC
B1o0dy_Trey edited this page Feb 6, 2020
·
11 revisions
使用IoC容器有如下几个步骤
- 使用@Named注解标注需要管理的bean。
- 设置bean的Scope属性(可选)
- 创建ApplicationContext实例,启动上下文
- 获取bean。
- 关闭上下文
将festival的jar包导入到项目中。
在src/main/java/bean目录下,新建一个ExampleBean类,并使用@Named注解标注,代码如下:
@Singleton
@Named
public class ExampleBean{}
@Configuration可以将一个类标注成配置类,只有在配置类中才可以编写工厂方法。
下面我们在src/main/java/bean下,新建一个ConfigurationBean类,代码如下:
@Configuration
public class ConfigurationBean{
@Named("factoryBean")
public ExampleBean factoryMethod(ExampleBean bean){
return bean;
}
}
工厂方法的产品bean的获取方法和普通的bean相同。
随后在src/main/java目录下,新建一个Example类,用于演示如何取出bean。代码如下
public class Example{
public static void main(String[] args){
AnnotationApplicationContext applicationContext = new AnnotationApplicationContext("bean");
ExampleBean bean = applicationContext.getBean(ExempleBean.class);
ExampleBean factoryBean = applicationContext.getBean("factoryBean");
applicationContext.close();
}
}
至此,大功告成。