1. Spring,SpringMVC 需要使用大量的配置文件(xml文件);
还需要配置各种对象,把使用的对象放入到spring容器中才能使用对象;
需要了解其他框架配置规则。
2. SpringBoot 就相当于不需要配置文件的Spring+SpringMVC,常用的框架和第三方库都已经配置好了。
3. SpringBoot开发效率高,使用方便多了。
JavaConfig: 使用java类作为xml配置文件的替代, 是配置spring容器的纯java的方式。 在这个java类这可以创建java对象,把对象放入spring容器中(注入到容器)。
使用两个注解:
1)@Configuration : 放在类的上面,表示这个类是作为配置文件使用的。
2)@Bean:放在方法的上面,声明对象,把方法返回值对象注入到容器中。
@Configuration
@importResource(value ={ "classpath:applicationContext.xml","classpath:beans.xml"})
@PropertySource(value = "classpath:config.properties")
@ComponentScan(basePackages = "com.lzq.vo")
public class SpringConfig {
@Bean
public Student createStudent(){
Student student = new Student(2, "lzq");
return student;
}
@Bean(name = "myStudent2")
public Student createStudent2(){
Student student = new Student(3, "lzq");
return student;
}
}
三、Hello SpringBoot
3.1 创建方式
第一种方式, 使用Spring提供的初始化器, 就是向导创建SpringBoot应用
地址: https://start.spring.io
国内地址:https://start.springboot.io
第二种方式,创建普通maven项目,添加SpringBoot框架支持,在pom中导入起步依赖starter
3.2 SpringBoot的配置文件配置文件名称: application
扩展名有: properties( k=v) ; yml ( k: v)
使用application.properties,或者application.yml
#设置端口号 server.port=8082 #设置访问应用上下文路径, contextpath server.servlet.context-path=/myboot3.2.1 多环境配置
有开发环境, 测试环境, 上线环境等。
每个环境有不同的配置信息, 例如端口, 上下文件, 数据库url,用户名,密码等等
使用多环境配置文件,可以方便的切换不同的配置。
使用方式: 创建多个配置文件
名称规则: application-环境名称.properties(yml)
创建开发环境的配置文件: application-dev.properties( application-dev.yml )
创建测试者使用的配置: application-test.properties
spring:
#激活application-dev.yml环境
profiles:
active: dev
3.3 @ConfigurationProperties
@ConfigurationProperties: 把配置文件的数据映射为java对象。
属性:prefix 配置文件中的某些key的开头的内容。
@Component
@ConfigurationProperties(prefix = "school")
public class SchoolInfo {
private String name;
}
#自定义key=value school.name=动力节点3.4 使用jsp
SpringBoot不推荐使用jsp ,而是使用Thymeleaf模板技术代替jsp。
1)加入处理jsp的依赖,负责编译jsp文件
org.apache.tomcat.embed tomcat-embed-jasper
2)如果需要使用servlet, jsp,jstl的功能,加入相关依赖
javax.servlet jstljavax.servlet javax.servlet-apijavax.servlet.jsp javax.servlet.jsp-api2.3.1
3)创建一个存放jsp的目录,一般叫做webapp,并添加为web资源目录
4)在pom.xml指定jsp文件编译后的存放目录。
src/main/webapp
meta-INF/resources
***.xml
3)创建pojo实体类Student;
4)创建Dao接口 StudentDao , 创建一个查询学生的方法;
方式一:
@Mapper:放在dao接口的上面, 每个接口都需要使用这个注解。
@Mapper
public interface StudentDao {
Student selectById(@Param("stuId") Integer id);
}
方式二:
@MapperScan:放在主启动类上,设置扫描包,不用每个接口都用@Mapper了
@SpringBootApplication
@MapperScan(basePackages = {"com.lzq.dao","com.lzq.mapper"})
public class Application {
}
方式三:
Mapper文件和Dao接口分开管理,把Mapper文件放在resources目录下(例如/mapper)
在application.properties文件中,指定mapper文件的目录:
#指定mapper文件的位置
mybatis.mapper-locations=classpath:mapper*.*
5)创建Dao接口对应的Mapper文件, xml文件, 写sql语句;
6)创建Service接口StudentService和实现类,调用Dao对象的方法,完成数据库的操作;
7)创建Controller类,访问Service。
8)写application.properties文件,配置数据库的连接信息。
#配置数据库 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8 #serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=5.2 MyBatis代码自动生成插件
Java反向工程,自动生成Dao接口和Mapper.xml文件。
1)在pom.xml配置
org.mybatis.generator mybatis-generator-maven-plugin1.3.7 GeneratorMapper.xml true true
2)GeneratorMapper.xml
3)启动插件
六、RestFul风格同SpringMVC。
在页面中或者ajax中,支持put,delete请求方式。
1)application.properties(yml) : 开启使用 HiddenHttpMethodFilter 过滤器;
#启用PUT delete请求方式 spring.mvc.hiddenmethod.filter.enabled=true
2)在请求页面表单中,添加隐藏域hidden,name="_method",value="put"或者"delete",发起这个请求使用post方式。
七、SpringBoot+RedisRedis : 一个NoSQL数据库, 常用作缓存使用 (cache),是一个中间件: 是一个独立的服务器。
java中著名的客户端: Jedis , lettuce , Redisson。
Redis的数据类型: string,hash,set,zset,list。
Spring,SpringBoot中有一个RedisTemplate(StringRedisTemplate),处理和Redis交互。
7.1 配置Windows版本的RedisRedis-x64-3.2.100.rar:解压缩到一个非中文目录
redis-server.exe:服务端,启动后不要关闭
redis-cli.exe:客户端,访问redis中的数据
redisclient-win32.x86_64.2.0.jar:Redis图形界面客户端
执行方式: 在这个文件所在的目录, 执行 java -jar redisclient-win32.x86_64.2.0.jar
7.2 SpringBoot中使用Redis1)Redis起步依赖: 直接在项目中使用RedisTemplate(StringRedisTemplate)
org.springframework.boot spring-boot-starter-data-redis
2)配置application.yml
#配置redis服务器信息 spring.redis.host=localhost spring.redis.port=6379 #spring.redis.password=
3)编写Controller测试
@RestController
public class RedisController {
//两种:RedisTemplate使用JDK序列化(序列化为字节,有乱码)
// StringRedisTemplate使用String序列化(序列化为字符串)
//注入 RedisTemplate
//泛型 key,value 都是 String ,或者 Object, 不写
@Resource
private RedisTemplate redisTemplate;
@Resource
private StringRedisTemplate stringRedisTemplate;
@RequestMapping("/add2Redis/{key}/{value}")
public String add2Redis(@PathVariable String key, @PathVariable String value){
ValueOperations stringStringValueOperations = stringRedisTemplate.opsForValue();
stringStringValueOperations.set(key, value);
//设置redisTemplate使用String序列化
//redisTemplate.setKeySerializer(new StringRedisSerializer());
//redisTemplate.setValueSerializer(new StringRedisSerializer());
//ValueOperations valueOperations = redisTemplate.opsForValue();
//valueOperations.set(key, value);
return "添加String类型数据到redis==》key:"+key+",value:"+value;
}
@RequestMapping("/getRedis/{key}")
public String getRedis(@PathVariable String key){
Object o = redisTemplate.opsForValue().get(key);
return "得到redis中数据==》key:"+key+",value:"+o;
}
@RequestMapping("/addJson2Redis")
public String addJson2Redis(){
User user = new User(1,"李四");
//设置redisTemplate key使用String序列化
redisTemplate.setKeySerializer(new StringRedisSerializer());
//设置redisTemplate value使用Json序列化
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(User.class));
redisTemplate.opsForValue().set("myUser", user);
return "添加Json类型数据到redis==》key:myUser,value:"+user;
}
@RequestMapping("/getJsonRedis")
public String getJsonRedis(){
//设置redisTemplate key使用String序列化
redisTemplate.setKeySerializer(new StringRedisSerializer());
//设置redisTemplate value使用Json序列化
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(User.class));
Object user = redisTemplate.opsForValue().get("myUser");
return "得到redis中Json数据==》key:myUser,value:"+user;
}
}
StringRedisTemplate : 把k,v 都是作为String处理, 使用的是String的序列化 , 可读性好;
RedisTemplate : 把k,v 经过了序列化存到redis。 k,v 是序列化的内容, 不能直接识别。
PS:查询Redis中数据,有则直接使用,没有则查询数据库;数据库中有则返回使用并加到Redis中,没有返回空并在Redis中添加一个该key的伪数据,防止”缓存穿透“,跳过缓存直接访问数据库,造成压力,并设置伪数据60秒销毁。
redisTemplate.opsForValue().set(key,new User(id,""), 60, TimeUnit.SECONDS);八、SpringBoot集成Dubbo 8.1 公共项目interfaceAPI
独立的maven项目: 定义了Service接口和pojo数据类
public class Student implements Serializable {
private static final long serialVersionUID = 1901229007746699151L;
private Integer id;
private String name;
}
public interface StudentService {
Student queryStudent(Integer id);
}
8.2 提供者Provider
SpringBoot项目,提供远程服务。
1)加入相关依赖
org.springframework.boot
spring-boot-starter-json
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.2.2
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-data-redis
groupId
dubbo-interfaceAPI
1.0-SNAPSHOT
org.apache.dubbo
dubbo-spring-boot-starter
2.7.8
org.apache.dubbo
dubbo-dependencies-zookeeper
2.7.8
pom
slf4j-log4j12
org.slf4j
2)编写Dao接口、mapper文件,实现API中的接口ServiceImpl(@DubboService)。
@DubboService(interfaceClass = StudentService.class, version = "1.0", timeout = 5000)
public class StudentServiceImpl implements StudentService{
@Override
public Student getByID(Integer id) {
return new Student(id, "李四", 24);
}
}
3)配置application.properties
#服务名称
spring.application.name=service-provider
#注册中心
dubbo.registry.address=zookeeper://localhost:2181
#配置扫描的包, 扫描的@DubboService
dubbo.scan.base-packages=com.lzq.service
#配置dubbo协议
#dubbo.protocol.name=dubbo
#dubbo.protocol.port=20881
#redis
spring.redis.host=localhost
spring.redis.port=6379
#spring.redis.password=123
#mybatis
mybatis.mapper-locations=classpath:mapper
//@DubboReference(interfaceClass = StudentService.class,version = "1.0")
@DubboReference(version = "1.0")
private StudentService studentService;
@RequestMapping("/get/{id}")
public String getByID(@PathVariable Integer id){
Student student = studentService.getByID(id);
return "调用远程接口,获取对象:"+student;
}
}
8.4 运行步骤
1)启动zookeeper
下载zookeeper(解压后把zoo_simple.cfg改为zoo.cfg),运行/bin/zkServer.cmd
2)启动提供者
3)启动消费者测试
九、Thymeleaf使用java开发的模板技术,在服务器端运行,把处理后的数据发送给浏览器。 基于Html语言,语法是应用在 html标签中。 SpringBoot框架集成Thymealeaf,使用Thymeleaf代替jsp。
1)依赖
org.springframework.boot spring-boot-starter-thymeleaf
2)在html中引入命名空间
百度 百度
默认视图解析器前缀:classpath:/templates/
后缀:.html
十、打包 10.1 war包1)pom.xml 指定打包文件名
myboot
2)指定jsp编译目录
src/main/webapp meta-INF/resources ***.xml src/main/resources ** @SpringBootApplication public class JspApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(JspApplication.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(JspApplication.class); } }
5)打包到target
6)把war放到tomcat等服务器的发布目录中。tomcat为例,myboot.war放到tomcat/webapps目录,启动tomcat。
10.2 jar包1)3)5)同上,
6)执行独立的springboot项目(内嵌tomcat),在cmd中:java -jar myboot.jar
十一、注解总结Spring + SpringMVC + SpringBoot
11.1 创建对象的@Controller:放在类的上面,创建控制器对象,注入到容器中;
@RestController:放在类的上面,创建控制器对象,注入到容器中。 作用:复合注解是@Controller , @ResponseBody, 使用这个注解类的,里面的控制器方法的返回值都是String数据;
@Service:放在业务层的实现类上面,创建service对象,注入到容器;
@Repository:放在dao层的实现类上面,创建dao对象,放入到容器。没有使用这个注解,是因为现在使用MyBatis框架, dao对象是MyBatis通过代理生成的。不需要使用@Repository。
@Component: 放在类的上面,创建此类的对象,放入到容器中。
11.2 赋值的@Value : 简单类型的赋值。
例如在属性的上面使用@Value("李四") private String name;
还可以使用@Value,获取配置文件的数据(properties或yml)。 @Value("${server.port}") private Integer port;
@Autowired: 引用类型赋值自动注入的,支持byName, byType. 默认是byType 。放在属性的上面,也可以放在setter 方法的上面。
@Qualifer: 给引用类型赋值,使用byName方式。 @Autowird, @Qualifer都是Spring框架提供的。
@Resource: 来自jdk中的定义, javax.annotation。 实现引用类型的自动注入, 支持byName, byType。默认是byName, 如果byName失败, 再使用byType注入,在属性上面使用。
11.3 其他@Configuration: 放在类的上面,表示这是个配置类,相当于xml配置文件
@Bean:放在方法的上面, 把方法的返回值对象,注入到spring容器中。
@importResource : 加载其他的xml配置文件, 把文件中的对象注入到spring容器中
@PropertySource : 读取其他的properties属性配置文件
@ComponentScan: 扫描器 ,指定包名,扫描注解的
@ResponseBody: 放在方法的上面,表示方法的返回值是数据,不是视图
@RequestBody : 把请求体中的数据,读取出来, 转为java对象使用。
@ControllerAdvice: 控制器增强, 放在类的上面, 表示此类提供了方法,可以对controller增强功能。
@ExceptionHandler : 处理异常的,放在方法的上面
@Transcational : 处理事务的, 放在service实现类的public方法上面, 表示此方法有事务
11.4 SpringBoot中的注解@SpringBootApplication : 放在启动类上面,
包含了@SpringBootConfiguration @EnableAutoConfiguration, @ComponentScan
11.5 MyBatis相关的注解@Mapper : 放在类的上面 , 让MyBatis找到接口, 创建他的代理对象
@MapperScan :放在主类的上面 , 指定扫描的包, 把这个包中的所有接口都创建代理对象,对象注入到容器中
@Param : 放在dao接口的方法的形参前面, 作为命名参数使用的。
11.6 Dubbo注解@DubboService: 在提供者端使用的,暴露服务的, 放在接口的实现类上面
@DubboReference: 在消费者端使用的, 引用远程服务, 放在属性上面使用。
@EnableDubbo : 放在提供者端主类上面, 表示当前引用启用Dubbo功能。



