在進行配置之前首先要了解springboot是如何使用純java代碼方式初始化一個bean的
以前的版本是在xml中使用beans標簽,在其里面配置bean,那么純Java代碼怎么實現呢?
答案就是使用@Configuration
注解和@Bean
,代碼如下:當然搜資料過程中你會學習到其他的知識,並嘗試使用
1.mybatis-spring-boot-stater的Maven依賴
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> </dependency>
2.配置數據源,這里使用的dbcp的數據源,具體大家可以看自己的情況來使用
在src/main/resource中,添加一個application.properties配置文件,這里面添加了一些數據庫連接的信息
########################################################
###datasource
########################################################
spring.datasource.url = jdbc:mysql://123.206.228.200:3306/test
spring.datasource.username = shijunjie
spring.datasource.password = ******
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.max-maxWait=100
spring.datasource.min-idle=8
spring.datasource.initial-size=10
2.1注入數據源
package me.shijunjie.config; import org.apache.commons.dbcp.BasicDataSource; 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; @Configuration @PropertySource("classpath:application.properties") public class DataSourceConfiguration { @Value("${spring.datasource.driverClassName}") private String driver; @Value("${spring.datasource.url}") private String url; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; @Value("${spring.datasource.max-active}") private int maxActive; @Value("${spring.datasource.max-idle}") private int maxIdel; @Value("${spring.datasource.max-maxWait}") private long maxWait; @Bean public BasicDataSource dataSource(){ BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setMaxActive(maxActive); dataSource.setMaxIdle(maxIdel); dataSource.setMaxWait(maxWait); dataSource.setValidationQuery("SELECT 1"); dataSource.setTestOnBorrow(true); return dataSource; } }
2.2MyBatis的配置
package me.shijunjie.config; import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.TransactionManagementConfigurer; @Configuration //加上這個注解,使得支持事務 @EnableTransactionManagement public class MybatisConfig implements TransactionManagementConfigurer { @Autowired private DataSource dataSource; @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource); } @Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactoryBean() { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); try { return bean.getObject(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } @Bean public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } }
2.3配置MyBatis配置文件的路徑,這個配置需要與上面的配置分開來寫,因為它們有着一個先后順序
package me.shijunjie.config; import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @AutoConfigureAfter(MybatisConfig.class) public class MyBatisMapperScannerConfig { @Bean public MapperScannerConfigurer mapperScannerConfigurer() { MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); //獲取之前注入的beanName為sqlSessionFactory的對象 mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory"); //指定xml配置文件的路徑 mapperScannerConfigurer.setBasePackage("me.shijunjie.dao"); return mapperScannerConfigurer; } }
2.4使用@Mapper注解來標識一個接口為MyBatis的接口,MyBatis會自動尋找這個接口
package me.shijunjie.dao; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import me.shijunjie.entity.Demo2; @Mapper public interface DemoDao2{ @Insert("insert into t_demo(tname) "+ "values(#{name})") int save(Demo2 demo); }
3.編寫Controller 和 Service 以及實體類
編寫實體類:
package me.shijunjie.entity; public class Demo2 { public Demo2() { } public Demo2(long id, String name) { this.id = id; this.name = name; } private long id; private String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
編寫service和實現類:
package me.shijunjie.service; import me.shijunjie.entity.Demo2; public interface DemoService { public void save(Demo2 demo); }
package me.shijunjie.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import me.shijunjie.dao.DemoDao2; import me.shijunjie.entity.Demo2; import me.shijunjie.service.DemoService; @Service public class DemoServiceImpl implements DemoService { @Autowired private DemoDao2 demoDao; public void save(Demo2 demo){ demoDao.save(demo); } }
編寫Controller
package me.shijunjie.controller; import javax.annotation.Resource; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import me.shijunjie.entity.Demo2; import me.shijunjie.service.DemoService; @RestController @RequestMapping("/demo") public class DemoController { @Resource private DemoService demoService; /** * 測試保存數據方法. * @return */ @RequestMapping("/save") public String save(){ Demo2 d = new Demo2(); d.setName("Angel2"); demoService.save(d);//保存數據. return "ok.DemoController.save"; } }
編寫入口類
package me.shijunjie.controller; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.web.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; import org.springframework.scheduling.annotation.EnableScheduling; @ComponentScan(basePackages={"me.shijunjie"}) // 掃描該包路徑下的所有spring組件 /*@EnableJpaRepositories("me.shijunjie.dao") // JPA掃描該包路徑下的Repositorie *//*@EntityScan("me.shijunjie.entity") // 掃描實體類 */@SpringBootApplication @EnableScheduling public class App extends SpringBootServletInitializer{ public static void main(String[] args) { SpringApplication.run(App.class, args); } }
測試
打開瀏覽器輸入http://localhost:8080/demo/save
成功