你要搞清楚自己人生的剧本:不是你父母的续集,不是你子女的前传,更不是你朋友的外篇。对待生命你不妨大胆冒险一点,因为好歹你要失去它。——源自尼采
开始前…
上面的金句是被转载很多的一句话,Spring Boot也有自己的舞台,只是这个舞台还没有大量展开。今天接着上一篇的内容开始正式的切入到Spring Boot,按照从Spring mvc里的xml配置导入使用到class类配置,最后使用starter的方法来实战,到最后,大家就能看到是怎么过渡到的了,还能体会到最后那快速的畅快感。
实战
1、建立启动类
建包: com.hjf.boot.demo.boot_mybatis
首先,建立StartApp启动程序类
// StartApp.class
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication //1
public class StartApp {
public static void main(String[] args) {
SpringApplication.run(StartApp.class,args);
}
}
说明:
- 1:用这个注解,就能实现自动扫描包和自动配置默认配置的功能,它包含了@ComponentScan和@EnableAutoConfiguration这两个注解,同时这个类自身也是一个配置类@Configuration,可以直接在这个类里添加@Bean来注入java bean,第一章用的注解组合实现的和这个注解功能是一致的,这也是Spring Boot官方推荐的配置方式,是不是觉得很简单,以前需要在xml里写自动扫描的bean,现在只需要一个注解就搞定,快速、快速、快速,重要的原则说三遍,这也是Spring Boot的目标。
2、建立演示用服务类
我们使用现在基本通用的设计模式来设计类,包含controller(我更喜欢叫api),dao,domain,service,每一个都只有一个类。
模型类:domain —> TestPOJO.class
public class TestPOJO {
private Long id;
private String name;
private int age;
//省略 get、set
}
服务类:service—> TestServices.class
import com.hjf.boot.demo.boot_mybatis.dao.TestDao;
import com.hjf.boot.demo.boot_mybatis.domain.TestPOJO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TestServices {
//1
@Autowired
private TestDao testDao;
public String show(){
return "hello world!";
}
public List<TestPOJO> showDao(int age){
return testDao.get(age);
}
}
说明:
- 1:这里提供两个方法,一个只是简单返回字符串,另个从mysql数据库里去取出数据显示。
接口控制器类:api—>TestController.class
import com.hjf.boot.demo.boot_mybatis.services.TestServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController //1
public class TestController {
@Autowired
private TestServices testServices; //2
@RequestMapping(value = "/show") //3
public String show(){
return testServices.show();
}
@RequestMapping(value = "/showDao") //4
public Object showDao(int age){
return testServices.showDao(age);
}
}
说明:
- 1:使用这个方法代表rest风格的控制器,这个是Spring MVC的特性。主要是方便不写@ResponseBody;
- 2:注入服务方法;
- 3:调用普通服务接口方法;
- 4:调用查询数据库接口方法。
文件结构配置完后,接下来我们开始配置链接数据库的dao接口和配置,这里就会有三种方法:
三板斧
板斧1:引用xml配置
在Spring Boot里其实是不推荐使用导入xml配置的,但不是说就不能导入xml,只能用starter,之前也看过有关的集成的文章,都是一笔带过,我还是那个感触,不能一篇文章就成功过的,反正我自己折腾了很久才成功。
第1步:添加pom依赖。
这需要添加mybatis相关的驱动依赖和jdbc连接池的依赖。
第2步:建立文件applicationContext.xml。
我们要在resources下新建applicationContext.xml并将上一章同名xml文件里的datasource和mybatis的配置放入这里(我们不用profile配置,直接使用datasource简单一点