標記在 方法上的時候,它會根據類型去spring容器中尋找 對於的形參並且注入。
1 @Repository(value="userDao") 2 public class UserDaoImpl extends SqlSessionDaoSupport implements IUserDao{ 3 4 // @Autowired 5 // @Qualifier(value="sqlsessionFactory11") 6 // private SqlSessionFactory asqlSessionFactory; 7 // 8 public User getOne(String uid) { 9 return this.getSqlSession().selectOne("cn.us.mybatis.getOne",uid); 10 } 11 12 public List<User> getAllUsers() { 13 Object obj=this.getSqlSession(); 14 return this.getSqlSession().selectList("cn.us.mybatis.getAllUsers"); 15 } 16 17 }
子類也可以,如果配置多個就會報錯。
SqlSessionDaoSupport 中有以下方法
1 @Autowired(required = false) 2 public final void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { 3 if (!this.externalSqlSession) { 4 this.sqlSession = new SqlSessionTemplate(sqlSessionFactory); 5 } 6 }
只能一個bean,根據 type 類型去匹配的
1 <bean id="sqlsessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" > 2 <property name="configLocation" value="classpath:sqlMapConfig.xml"></property> 3 <property name="dataSource" ref="dataSource"></property> 4 </bean>
因為 required=false,如果spring找不到的話會賦空值進去
如果沒有@Autowired(required = false)的話,那么UserDaoImpl 不能繼承
SqlSessionDaoSupport 了,可以用組合的方式
然后
@Autowired
private SqlSessionFactory sqlSessionFactory;
然后在spring配置文件中,<bean id=...>配置上 SqlSessionFactory