Property ‘sqlSessionFactory‘ or ‘sqlSessionTemplate‘ are required

场景:

springboot集成mybatis-plus的时候报以下异常

 WARN  [RMI TCP Connection(3)-127.0.0.1] o.s.b.c.e.AnnotationConfigEmbeddedWebApplicationContext.(): Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.cr.dgp.web.config.security.WebSecurityConfig': Unsatisfied dependency expressed through method 'setUserDetailsService' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.cr.dgp.web.config.security.UserDetailsServiceImpl': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.bcy.ipg.user.service.impl.UserServiceImpl' defined in URL [jar:file:/E:/IdeaProjects/dgp_v2.0/dgp-web/target/crDgp/WEB-INF/lib/ipg-user-center-1.0-SNAPSHOT.jar!/com/bcy/ipg/user/service/impl/UserServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.bcy.ipg.user.service.impl.RoleUserServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'roleUserMapper' defined in URL [jar:file:/E:/IdeaProjects/dgp_v2.0/dgp-web/target/crDgp/WEB-INF/lib/ipg-user-center-1.0-SNAPSHOT.jar!/com/bcy/ipg/user/mapper/RoleUserMapper.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required

大致意思是:初始化方法调用失败;嵌套异常是java.lang.IllegalArgumentException:属性'sqlSessionFactory'或'sqlSessionTemplate'是必需的

此处有两种解决方法:

第一种是引用一下依赖,它会帮我们自动注入sqlSessionFactory

<!--        springBoot集成mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus-boot-starter.version}</version>
        </dependency>

第二种方法时手动注入



import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@Slf4j
@Qualifier("dataSourceConfig")
@MapperScan(basePackages = "com.cr.*")
public class DataSourceConfig {

    @Value("${show.sql}")
    private Boolean value;

    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.main")
    @Qualifier("mainDataSource")
    public DataSource mainDataSource() {
        return new DruidDataSource();
    }
    
    @Primary
    @Bean
    public JdbcTemplate JdbcTemplate() {
        return new JdbcTemplate(mainDataSource());
    }
    
    @Bean(name = "dynamicDataSource")
    @Qualifier("dynamicDataSource")
    public DynamicDataSource dynamicDataSource() {

        Map<Object, Object> targetDataSources = new HashMap<>();
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setDebug(false);
        //配置缺省的数据源
        // 默认数据源配置 DefaultTargetDataSource
        dynamicDataSource.setDefaultTargetDataSource(mainDataSource());
        //额外数据源配置 TargetDataSources
        targetDataSources.put("mainDataSource", mainDataSource());
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.afterPropertiesSet();
        return dynamicDataSource;
    }

   /**
    * 主要看的是这个方法
    */
    @Bean
    public SqlSessionFactory sqlSessionFactory(@Qualifier("globalConfig") GlobalConfig globalConfig)
            throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dynamicDataSource());
        //此处设置为了解决找不到mapper文件的问题
        sqlSessionFactoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/**/*Mapper.xml"));

        MybatisConfiguration configuration = new MybatisConfiguration();

        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        // 查询时显示字段结果为 null 的字段,默认不显示
        configuration.setCallSettersOnNulls(true); 
        sqlSessionFactoryBean.setConfiguration(configuration);

        sqlSessionFactoryBean.setPlugins(new Interceptor[]{
        });
        sqlSessionFactoryBean.setGlobalConfig(globalConfig);
        return sqlSessionFactoryBean.getObject();
    }
    
   
    @Bean("globalConfig")
    public GlobalConfig globalConfig() {
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setMetaObjectHandler(new MyMetaObjectHandler());

        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        dbConfig.setLogicDeleteValue("1");
        dbConfig.setLogicNotDeleteValue("0");
        //#主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
        dbConfig.setIdType(IdType.AUTO);
        //#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
        dbConfig.setInsertStrategy(FieldStrategy.NOT_NULL);
        //#是否开启大写命名,默认不开启
        dbConfig.setCapitalMode(false);

        globalConfig.setDbConfig(dbConfig);
        return globalConfig;
    }
    
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值