-
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。
- 关闭上下文
首先我们应该先将依赖导入到maven工程。在pom.xml文件中添加以下内容
<!-- https://mvnrepository.com/artifact/com.github.bdqfork/festival-core -->
<dependency>
<groupId>com.github.bdqfork</groupId>
<artifactId>festival-core</artifactId>
<version>0.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.bdqfork/festival-parent -->
<dependency>
<groupId>com.github.bdqfork</groupId>
<artifactId>festival-context</artifactId>
<version>0.3</version>
</dependency>
在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(ExampleBean.class);
ExampleBean factoryBean = applicationContext.getBean("factoryBean");
applicationContext.close();
}
}
至此,大功告成。