spring源码之模拟mybatis第三方对象注入
生活随笔
收集整理的這篇文章主要介紹了
spring源码之模拟mybatis第三方对象注入
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
有下面幾種方法
看到這幾種方式的時候,需要我們自己思考一下,在注冊這個對象之前,是需要自己手動生成的。
那么使用注解Service和XML的方式肯定是不行的,因為這個只是把一個類交給了spring容器管理,并不是生成的對象交給他。所以前兩種方式不可行。
第六種方式也是不行的,至于為什么不行,我們到后面再說。
注解(@Bean)
public class BatisConfig {@Beanpublic TMapper getTMapper(){TMapper tMapper = (TMapper) MySqlSession.getMapper(TMapper.class);return tMapper;}}@Testpublic void customBatis(){AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BatisConfig.class);TMapper mapper = context.getBean(TMapper.class);mapper.queryMap("1");}//打印結果 假裝連接數據庫 假裝執行了查詢語句select * from t where id = ${id} 假裝返回了JSON串FactoryBean
@Component public class MyFactoryBean implements FactoryBean {@Overridepublic Object getObject() throws Exception {System.out.println("實例化了Mapper");TMapper tMapper = (TMapper) MySqlSession.getMapper(TMapper.class);return tMapper;}@Overridepublic Class<?> getObjectType() {return TMapper.class;} }@Testpublic void customBatis(){AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();context.scan("com.spring.batis");context.refresh();TMapper mapper = context.getBean(TMapper.class);mapper.queryMap("1");}//打印結果 假裝連接數據庫 假裝執行了查詢語句select * from t where id = ${id} 假裝返回了JSON串spring 容器api手動注入
@Testpublic void customBatis(){AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();TMapper tMapper = (TMapper) MySqlSession.getMapper(TMapper.class);context.getBeanFactory().registerSingleton("t", tMapper);context.refresh();TMapper mapper = context.getBean(TMapper.class);mapper.queryMap("1");} //打印結果 假裝連接數據庫 假裝執行了查詢語句select * from t where id = ${id} 假裝返回了JSON串總結
以上是生活随笔為你收集整理的spring源码之模拟mybatis第三方对象注入的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小程序实现分享朋友圈分享好友功能
- 下一篇: 怎么利用代理IP优化网络爬虫