目录
3.6 ComnandLineRunner 接口,ApplcationRunner接口
一、为什么使用SpringBoot
1. Spring,SpringMVC 需要使用大量的配置文件(xml文件);
还需要配置各种对象,把使用的对象放入到spring容器中才能使用对象;
需要了解其他框架配置规则。
2. SpringBoot 就相当于不需要配置文件的Spring+SpringMVC,常用的框架和第三方库都已经配置好了。
3. SpringBoot开发效率高,使用方便多了。
二、JavaConfig
JavaConfig: 使用java类作为xml配置文件的替代, 是配置spring容器的纯java的方式。 在这个java类这可以创建java对象,把对象放入spring容器中(注入到容器)。
使用两个注解:
1)@Configuration : 放在类的上面,表示这个类是作为配置文件使用的。
2)@Bean:放在方法的上面,声明对象,把方法返回值对象注入到容器中。
/**
* Configuration:表示当前类是作为配置文件使用的。 就是用来配置容器的
* 位置:在类的上面
*
* SpringConfig这个类就相当于beans.xml
*/
@Configuration
/**
* ImportResource作用导入其他的xml配置文件
* <import resources="其他配置文件"/>
*/
@ImportResource(value ={ "classpath:applicationContext.xml","classpath:beans.xml"})
@PropertySource(value = "classpath:config.properties")
@ComponentScan(basePackages = "com.lzq.vo")
public class SpringConfig {
/**
* 创建方法,方法的返回值是对象。 在方法的上面加入@Bean
* 方法的返回值对象就注入到容器中。
*
* @Bean: 把对象注入到spring容器中。 作用相当于<bean>
*
* 位置:方法的上面
*
* 说明:@Bean,不指定对象的名称,默认是方法名是 id
*
*/
@Bean
public Student createStudent(){
Student student = new Student(2, "lzq");
return student;
}
/***
* 指定对象在容器中的名称(指定<bean>的id属性)
* @Bean的name属性,指定对象的名称(id)
*/
@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=/myboot
3.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文件
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
2)如果需要使用servlet, jsp,jstl的功能,加入相关依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
3)创建一个存放jsp的目录,一般叫做webapp,并添加为web资源目录
4)在pom.xml指定jsp文件编译后的存放目录。
<!--指定jsp编译后的存放目录-->
<resources>
<resource>
<!--源目录-->
<directory>src/main/webapp</directory>
<!--存放目录-->
<targetPath>META-INF/resources</targetPath>
<!--指定处理的文件和目录-->
<includes>
<include>**/*.*</include>
</includes>
</resource>
5)创建Controller, 访问jsp
@Controller
public class JspController {
@RequestMapping("/jsp")
public String jspController(HttpServletRequest request){
request.setAttribute("data","hello JSP");
return "index";
}
}
6)在application.yml文件中配置视图解析器
spring:
#配置视图解析器
mvc:
view:
# / = src/main/webapp
prefix: /
suffix: .jsp
3.5 使用容器
通过SpringApplication.run(Application.class, args) 返回值获取容器。
@SpringBootApplication
public class SpringbootFirstApplication {
public static void main(String[] args) {
//获取容器对象
ApplicationContext ac = SpringApplication.run(SpringbootFirstApplication.class, args);
Student o = (Student) ac.getBean("student");
}
}
3.6 ComnandLineRunner 接口,ApplcationRunner接口
这两个接口都有一个run方法。 执行时间在容器对象创建好后, 自动执行run()方法。 可以完成自定义的在容器对象创建好后的一些操作。
@SpringBootApplication
public class SpringbootFirstApplication implements CommandLineRunner {
public static void main(String[] args) {
//获取容器对象
System.out.println("准备创建容器对象");
ApplicationContext ac = SpringApplication.run(SpringbootFirstApplication.class, args);
Student o = (Student) ac.getBean("student");
System.out.println(o);
System.out.println("容器对象创建之后");
}
@Override
public void run(String... args) throws Exception {
//可做自定义的操作,比如读取文件、数据库等
System.out.println("容器创建好之后执行的方法");
}
}
四、Web组件(拦截器,Servlet,过滤器)
4.1 拦截器
拦截器是SpringMVC中一种对象,能拦截对Controller的请求。
拦截器框架中有系统的拦截器,还可以自定义拦截器,实现对请求预先处理。
4.1.1 SpringMVC实现自定义拦截器:
1)实现SpringMVC框架的HandlerInterceptor接口
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("执行了LoginInterceptor中的preHandle");
return false;
}
}
2)在SpringMVC的配置文件中,声明拦截器
<mvc:interceptors>
<mvc:interceptor>
<mvc:path="url" />
<bean class="拦截器类全限定名称"/>
</mvc:interceptor>
</mvc:interceptors>
4.1.2 SpringBoot实现自定义拦截器:
1)实现SpringMVC框架的HandlerInterceptor接口,同上。
2)在JavaConfig配置类中实现 WebMvcConfigurer 接口的 addInterceptors() 方法
@Configuration
public class MyAppConfig implements WebMvcConfigurer {
//添加拦截器对象,注入到容器中
@Override
public void addInterceptors(InterceptorRegistry registry) {
HandlerInterceptor interceptor = new LoginInterceptor();
registry.addInterceptor(interceptor)
.addPathPatterns("/user/**")//拦截的请求
.excludePathPatterns("/user/login");//放行的请求
WebMvcConfigurer.super.addInterceptors(registry);
}
}
4.2 Servlet
1)创建自定义Servlet类,继承HttpServlet。
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
//super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//使用HttpServletResponse输出数据,应答结果
//resp.setContentType("text/html;charset=utf-8");//默认编码为ISO-8859-1
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("===执行的是Servlet===");
out.flush();
out.close();
//super.doPost(req, resp);
}
}
2) 在JavaConfig配置类中注册Servlet。
@Configuration
public class MyAppConfig {
//定义方法,注册Servlet对象
@Bean
public ServletRegistrationBean servletRegistrationBean(){
//public ServletRegistrationBean(T servlet, String... urlMappings)
//第一个参数是 Servlet对象, 第二个是url地址
//ServletRegistrationBean bean = new ServletRegistrationBean( new MyServlet(),"/myservlet");
//或者
ServletRegistrationBean bean = new ServletRegistrationBean();
bean.setServlet( new MyServlet());
bean.addUrlMappings("/login","/test"); // <url-pattern>
return bean;
}
}
4.3 过滤器
Filter是Servlet规范中的过滤器,可以处理请求, 对请求的参数, 属性进行调整。 常常在过滤器中处理字符编码。
1)创建自定义过滤器类,实现Filter接口。
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("执行了MyFilter,doFilter ");
filterChain.doFilter(servletRequest,servletResponse);
}
}
2) 在JavaConfig配置类中注册Filter。
@Configuration
public class MyAppConfig {
//注册自定义过滤器
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter( new MyFilter());
bean.addUrlPatterns("/user2/*");
return bean;
}
}
4.4 字符集过滤器
CharacterEncodingFilter : 解决post请求中乱码的问题。
方式一:
1)配置注册自定义字符集过滤器。
@Configuration
public class MyAppConfig {
//注册Filter,配置字符集过滤器
@Bean
public FilterRegistrationBean filterRegistrationBean2(){
FilterRegistrationBean reg = new FilterRegistrationBean();
//使用框架中的过滤器类
CharacterEncodingFilter filter = new CharacterEncodingFilter();
//指定使用的编码方式
filter.setEncoding("utf-8");
//指定request , response都使用encoding的值
filter.setForceEncoding(true);
reg.setFilter(filter);
//指定 过滤的url地址
reg.addUrlPatterns("/*");
return reg;
}
}
2)修改application.properties文件, 让自定义的过滤器起作用。
#SpringBoot中默认已经配置了CharacterEncodingFilter。 编码默认ISO-8859-1
#设置enabled=false 作用是关闭系统中配置好的过滤器, 使用自定义的CharacterEncodingFilter
server.servlet.encoding.enabled=false
方式二:修改application.properties文件(推荐)
#让系统的CharacterEncdoingFilter生效
server.servlet.encoding.enabled=true
#指定使用的编码方式
server.servlet.encoding.charset=utf-8
#强制request,response都使用charset属性的值
server.servlet.encoding.force=true
五、SpringBoot+MyBatis操作数据库
5.1 步骤
1)MyBatis起步依赖: 完成mybatis对象自动配置, 对象放在容器中;MySQL依赖;
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2)pom.xml 指定把src/main/java目录中的xml文件包含到classpath中;
<!--资源过滤-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
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/*.xml
#指定mybatis的日志
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
在pom.xml中指定 把resources目录中的文件, 编译到目标目录中:
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
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配置
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<configuration>
<!--配置文件的位置(项目根目录)-->
<configurationFile>GeneratorMapper.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
2)GeneratorMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 指定连接数据库的JDBC驱动包所在位置,指定到你本机的完整路径 -->
<classPathEntry location="D:\Program Files\maven\apache-maven-3.8.4\repository\mysql\mysql-connector-java\8.0.28\mysql-connector-java-8.0.28.jar"/>
<!-- 配置table表信息内容体,targetRuntime指定采用MyBatis3的版本 -->
<context id="tables" targetRuntime="MyBatis3">
<!-- 抑制生成注释,由于生成的注释都是英文的,可以不让它生成 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 配置数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis"
userId="root"
password="">
</jdbcConnection>
<!-- 生成model类,targetPackage指定model类的包名, targetProject指定生成的model放在eclipse的哪个工程下面-->
<javaModelGenerator targetPackage="com.lzq.pojo"
targetProject="src\main\java">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="false" />
</javaModelGenerator>
<!-- 生成MyBatis的Mapper.xml文件,targetPackage指定mapper.xml文件的包名, targetProject指定生成的mapper.xml放在eclipse的哪个工程下面 -->
<sqlMapGenerator targetPackage="com.lzq.dao" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成MyBatis的Mapper接口类文件,targetPackage指定Mapper接口类的包名, targetProject指定生成的Mapper接口放在eclipse的哪个工程下面 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.lzq.dao" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 数据库表名及对应的Java模型类名 -->
<table tableName="teacher" domainObjectName="Teacher"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
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方式。
<form action="post">
<input type=”hidden” name=”_method” value=”put”>
</form>
七、SpringBoot+Redis
Redis : 一个NoSQL数据库, 常用作缓存使用 (cache),是一个中间件: 是一个独立的服务器。
java中著名的客户端: Jedis , lettuce , Redisson。
Redis的数据类型: string,hash,set,zset,list。
Spring,SpringBoot中有一个RedisTemplate(StringRedisTemplate),处理和Redis交互。
7.1 配置Windows版本的Redis
Redis-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中使用Redis
1)Redis起步依赖: 直接在项目中使用RedisTemplate(StringRedisTemplate)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
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<String, String> 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项目: 定义了Dao、Service接口和pojo数据类
public class Student implements Serializable {
private static final long serialVersionUID = 1901229007746699151L;
private Integer id;
private String name;
}
public interface StudentDao {
Student queryStudent(Integer id);
int addUser(Student student);
}
public interface StudentService {
Student queryStudent(Integer id);
}
8.2 提供者Provider
SpringBoot项目,提供远程服务。
1)加入相关依赖
<!--使用redis时Jackson2JsonRedisSerializer需要用到jackson-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--加入公共项目的gav-->
<dependency>
<groupId>groupId</groupId>
<artifactId>dubbo-interfaceAPI</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--dubbo依赖-->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.8</version>
</dependency>
<!--zookeeper依赖-->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-dependencies-zookeeper</artifactId>
<version>2.7.8</version>
<type>pom</type>
<exclusions>
<!-- 排除log4j依赖 否则会与上面的重复导入报错 -->
<exclusion>
<artifactId>slf4j-log4j12</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
2)编写mapper文件,实现API中的接口ServiceImpl(@DubboService)。
/**
* 使用dubbo中的注解暴露服务
* @Component 可以不用加
*/
@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/*.xml
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#datasource
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=
4)在主启动类上加 @EnableDubbo
8.3 消费者Consumer
SpringBoot项目,使用远程服务。
1)添加相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--加入公共项目的gav-->
<dependency>
<groupId>groupId</groupId>
<artifactId>dubbo-interfaceAPI</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--dubbo依赖-->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.8</version>
</dependency>
<!--zookeeper依赖-->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-dependencies-zookeeper</artifactId>
<version>2.7.8</version>
<type>pom</type>
<exclusions>
<!-- 排除log4j依赖 否则会与上面的重复导入报错 -->
<exclusion>
<artifactId>slf4j-log4j12</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2)配置application.properties
server.port=8082
server.servlet.context-path=/dubbo
#指定服务名称
spring.application.name=consumer
#指定注册中心
dubbo.registry.address=zookeeper://localhost:2181
dubbo.scan.base-packages=com.lzq.controller
3)编写Controller测试(@DubboReference)
@RestController
public class DubboController {
/**
* 引用远程服务, 把创建好的代理对象,注入给studentService
*/
//@DubboReference(interfaceClass = StudentService.class,version = "1.0")
/**
* 没有使用interfaceClass,默认的就是 引用类型的 数据类型
*/
@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)依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2)在html中引入命名空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<div th:text="${data}"></div>
<div th:utext="${data}"></div>
<hr>
<h1 th:each="user:${users}" th:text="${user}"></h1>
<hr>
<h1 th:each="user1:${user}" th:text="${user1}"></h1>
<hr>
<a th:href="${href}">百度</a>
<a th:href="@{/href}">百度</a>
</body>
默认视图解析器前缀:classpath:/templates/
后缀:.html
十、打包
10.1 war包
1)pom.xml 指定打包文件名
<build>
<!--打包后的文件名称-->
<finalName>myboot</finalName>
</build>
2)指定jsp编译目录
<resources>
<resource>
<directory>src/main/webapp</directory>
<targetPath>META-INF/resources</targetPath>
<includes>
<include>**/*.*</include>
</includes>
</resource>
<!--使用了mybatis ,而且mapper文件放在src/main/java目录-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<!--把src/main/resources下面的所有文件,都包含到classes目录-->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
3)pom.xml 指定打包方式
<!--打包类型-->
<packaging>war</packaging>
4)主启动类继承SpringBootServletInitializer
/**
* SpringBootServletInitializer: 继承这个类, 才能使用独立tomcat服务器
*/
@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功能。
SpringBoot 如何实现自动装配
自动装配:通过注解或者一些简单的配置就能在 SpringBoot 的帮助下实现某块功能。
核心注解@SpringBootApplication:
@Configuration
在上下文中注册额外的 bean 或导入其他配置类
@EnableAutoConfiguration
启用 SpringBoot 的自动配置机制
@ComponentScan
扫描被@Component
(@Service
,@Controller
)注解的 bean
Spring Boot 通过@EnableAutoConfiguration
开启自动装配,通过 SpringFactoriesLoader 最终加载META-INF/spring.factories
中的自动配置类实现自动装配,自动配置类其实就是通过@Conditional
按需加载的配置类,想要其生效必须引入spring-boot-starter-xxx
包实现起步依赖。