FactoryBean 定义
public interface FactoryBean<T> {
@Nullable
T getObject() throws Exception;
@Nullable
Class<?> getObjectType();
default boolean isSingleton() {
return true;
}
}
- FactoryBean是一个泛型类的接口
- FactoryBean产生的对象默认是单例的
FactoryBean 的使用
Service 类
public interface IService {
void service();
}
public class IndexService implements IService {
@Override
public void service() {
System.out.println("service");
}
}
FactoryBeanTest 类
@Component
public class FactoryBeanTest implements FactoryBean{
@Override
public Object getObject() throws Exception {
return new IndexService();
}
@Override
public Class<?> getObjectType() {
return IndexService.class;
}
}
Appconfig 类
@Configuration
@ComponentScan("com.ktcatv")
public class Appconfig {
}
Test 类
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext configApplicationContext = new AnnotationConfigApplicationContext(Appconfig.class);
IService service = (IService) configApplicationContext.getBean("factoryBeanTest");
service.service();
Object bean = configApplicationContext.getBean("&factoryBeanTest");
System.out.println(bean);
}
}