众所周知,将对象交给spring管理有三种方法
1. @Bean, 即
public class AppConfig {
@Bean
AccDataCountMapper accDataCountMapper(){
//实例化一个 AccDataCountMapper 对象
AccDataCountMapper accDataCountMapper = (AccDataCountMapper) Proxy.newProxyInstance(SelfFactoryBean.class.getClassLoader(), new Class[]{AccDataCountMapper.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//先不做实现
return null;
}
});
return accDataCountMapper;
}
}
问题来了,如果只有一个两个mapper,还好,一堆的话,不是要写到吐。不便于扩展。
2.注册
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
context.getBeanFactory().registerSingleton("accMapper", AccDataCountMapper.class);
通过这种方式直接注册了,就失去了交给spring 管理的意义了。
3.FactoryBean
public class SelfFactoryBean implements FactoryBean {
@Override
public Object getObject() throws Exception {
//实例化一个 AccDataCountMapper 对象
AccDataCountMapper accDataCountMapper = (AccDataCountMapper)Proxy.newProxyInstance(SelfFactoryBean.class.getClassLoader(), new Class[]{AccDataCountMapper.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//先不做实现
return null;
}
});
return accDataCountMapper;
}
@Override
public Class<?> getObjectType() {
return AccDataCountMapper.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
当然,目前还是静态的,即通过指定类。
修改下
public class SelfFactoryBean implements FactoryBean {
//动态实例化
private Class