@Autowired(required = false)详解编程语言

标记在 方法上的时候,它会根据类型去spring容器中寻找 对于的形参并且注入。

 @Repository(value="userDao") 
 public class UserDaoImpl extends SqlSessionDaoSupport implements IUserDao{ 
      
 //    @Autowired 
 //    @Qualifier(value="sqlsessionFactory11") 
 //    private SqlSessionFactory asqlSessionFactory; 
 //     
     public User getOne(String uid) { 
         return this.getSqlSession().selectOne("cn.us.mybatis.getOne",uid); 
     } 
  
     public List<User> getAllUsers() { 
         Object obj=this.getSqlSession(); 
         return this.getSqlSession().selectList("cn.us.mybatis.getAllUsers"); 
     } 
  
 }

子类也可以,如果配置多个就会报错。

SqlSessionDaoSupport 中有以下方法
   @Autowired(required = false) 
   public final void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { 
     if (!this.externalSqlSession) { 
       this.sqlSession = new SqlSessionTemplate(sqlSessionFactory); 
     } 
   }

只能一个bean,根据 type 类型去匹配的

     <bean id="sqlsessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" > 
         <property name="configLocation" value="classpath:sqlMapConfig.xml"></property> 
         <property name="dataSource" ref="dataSource"></property> 
     </bean>

 因为 required=false,如果spring找不到的话会赋空值进去

[email protected](required = false)的话,那么UserDaoImpl 不能继承

SqlSessionDaoSupport 了,可以用组合的方式 

然后
@Autowired
private SqlSessionFactory sqlSessionFactory;

然后在spring配置文件中,<bean id=…>配置上 SqlSessionFactory 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/17203.html

(0)
上一篇 2021年7月19日 19:57
下一篇 2021年7月19日 19:57

相关推荐

发表回复

登录后才能评论