基于maven管理的spring-mybatis的整合如何实现零配置

最近发现maven零配置挺流行,但实际摸索之后个人感觉没有之前传统的直接写配置文件来的方便,二者最主要的区别就是将maven的ApplicationContext.xml文件通过代码的方式实现,其它的一些调用不变。

代码结构目录如下

import java.io.IOException;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@PropertySource("classpath:db.properties")
@MapperScan(basePackages= {"com.dao"})
@ComponentScan(basePackages = { "com" })
@EnableTransactionManagement
public class ApplicationContext {

    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    //1、配置数据源,这里使用的是阿里的DruidDataSource
    @Bean
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
    //2、创建sqlSessionFactory
    @Bean
    public SqlSessionFactoryBean factory() throws IOException {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource());
        factory.setTypeAliasesPackage("com.entity");
        factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/mappers/*Mapper.xml"));
        return factory;

    }
    //3、事务管理,配个数据源就可以了
    @Bean
    public DataSourceTransactionManager transactionManager() {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource());
        return transactionManager;
    }
 }

测试类不要忘记加这两个注解:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= {ApplicationContext.class})

猜你喜欢

转载自blog.csdn.net/weixin_42813949/article/details/81604570
今日推荐