第一步:
Spring配置类,主要目的为了把注解所标记的Bean扫描到IOC容器中
第二步:把SqlSessionFactoryBean交给Spring进行实例化,
但是需要进行依赖注入,也就是DataSource
package com.ligong.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
/**
* project : spring_01
* <p>
* 第一步:
* 把SqlSessionFactoryBean交给SpringIOC容器去管理,
* 然后由Spring去调用SqlSessionFactoryBean实现FactoryBean接口中的方法,
* 也就是getObject所返回的的SqlSessionFactory对象就会放入到容器中,
* 当然其声明周期中需要进行依赖注入也就是DataSource对象,这个类的实例也是交给IOC容器去管理
* 第二步骤:
* 引入DataSource所需要的外部信息。
*
* </p>
*
* @author
* @date 2022-02-10【星期四】
**/
@Configuration
@PropertySource("classpath:jdbc.properties")
public class MyBatisConfig {
@Value("${jdbc.driverClassName}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource dataSource(){
DruidDataSource dataSource=new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean;
}
}
结果展示