spring进阶
第一节 : spring boot 系列之ssm项目实战
1.spring boot 介绍
特点
- 创建独立的spring容器应用程序
- 内嵌容器(tomcat,jetty,undertow)无需war部署
- 自动配置spring配置
- 简化maven配置
- 开箱即用,无需配置xml
2.idea创建springboot web 项目
2.1.1 spring boot 如何实现一个spring MVC
2.1.2 Idea 创建spring boot项目:
- spring Initializr
- web -->web:spring boot SNAPSHOT
2.1.3第一个例子:
- 创建controller(引入 @RestController)
- 编写方法(@RequestMapping ,@GetMappings,@PostMapping)
- 介绍 application.properties中修改port,context-path以及banner.location的方法。
@RestController
public class IndexController {
@GetMapping("index")
public Map<String, String> index() {
Map<String, String> map = new HashMap<String, String>();
map.put("悟空", "是只猴子");
map.put("鲁班", "是个英雄");
return map;
}
@PostMapping("/index2")
public Map<String, String> index2() {
Map<String, String> map = new HashMap<String, String>();
map.put("悟空", "是只猴子");
map.put("鲁班", "是个英雄");
return map;
}
}
3.mybatis
3.1 springboot 如何实现mybaatis
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
3.2 idea View DataBase 窗口连接mysql
3.3 创建pojo/JavaBean/Po [User.java]
3.4 创建dao层 UserMapping.java(Interface)
@Mapper
public interface UserMapping {
@Select("select * from user where username= #{name}")
public List<User> getUserByUsesrName(String name);
}
3.5 service层 UserService 并 implements dao接口方法
@Service
public class UserService implements UserMapping {
@Autowired
UserMapping userMapping;
@Override
public List<User> getUserByUsesrName(String name) {
return userMapping.getUserByUsesrName(name);
}
}
3.6 编写controller层
/**
* @Controller 使用 @RestController 可以在方法中省略 @Response的编写,
因其内部使用 @Controller和 @Reposence注解
*/
@RestController
public class IndexController {
@Autowired
UserService userService;
@GetMapping("/getuser")
public List<User> getUserByUsesrName(String name) {
return userService.getUserByUsesrName("lijwen");
}
}
3.7 配置datasource
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3.8 编写controller
@EnableAutoConfiguration
@ComponentScan(basePackages ={"com.springboot.demo.controller","com.springboot.demo.service"})
@MapperScan(basePackages = "com.springboot.demo.dao")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}