新建一个maven项目,导入jar包
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
实现FactoryBean接口
/**
* 颜色工厂bean
* @author: wangshuang
* @date: 2020/5/21
*/
public class ColorFactoryBean implements FactoryBean<Color> {
/**
* 返回color对象,对象会添加到容器中
* @return
* @throws Exception
*/
public Color getObject() throws Exception {
System.out.println("ColorFactoryBean调用了getObject");
return new Color();
}
/**
*
* @return
*/
public Class<?> getObjectType() {
return null;
}
/**
* 是否是单例
* true:是单例,在容器中只会保留一份
* false:不是单例,每次获取都会创建一个新的
* @return
*/
public boolean isSingleton() {
return false;
}
}
@Configurable
public class MainConfig {
@Bean
public ColorFactoryBean colorFactoryBean() {
return new ColorFactoryBean();
}
}
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Object beanByName = annotationConfigApplicationContext.getBean("colorFactoryBean");
System.out.println("beanByName的类型"+beanByName.getClass());
Object beanByName1 = annotationConfigApplicationContext.getBean("&colorFactoryBean");
System.out.println("beanByName1的类型"+beanByName1.getClass());
ColorFactoryBean beanByType = annotationConfigApplicationContext.getBean(ColorFactoryBean.class);
System.out.println("beanByType的类型"+beanByType.getClass());
}