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);
}
}
複製代碼