Spring Boot企业常用的starter示例详解
SpringBoot简介#
SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Boot致力于在蓬勃发展的快速应用开发领域(rapidapplicationdevelopment)成为领导者。
SpringBoot让我们的Spring应用变的更轻量化。比如:你可以仅仅依靠一个Java类来运行一个Spring引用。你也可以打包你的应用为jar并通过使用java-jar来运行你的SpringWeb应用。
SpringBoot的主要优点:
- 为所有Spring开发者更快的入门
- 开箱即用,提供各种默认配置来简化项目配置
- 内嵌式容器简化Web项目
- 没有冗余代码生成和XML配置的要求
在下面的代码中只要有一定基础会发现这写代码实例非常简单对于开发者来说几乎是“零配置”。
SpringBoot运行#
开发工具:jdk8,IDEA,STS,eclipse(需要安装STS插件)这些都支持快速启动SpringBoot工程。我这里就不快速启动了,使用maven工程。学习任何一项技术首先就要精通HelloWord,那我们来跑个初体验。
首先只用maven我们创建的maven工程直接以jar包的形式创建就行了,首先我们来引入SpringBoot的依赖
首先我们需要依赖SpringBoot父工程,这是每个项目中必须要有的。
org.springframework.boot spring-boot-starter-parent 2.0.5.RELEASE UTF-8 UTF-8 1.8
我们启动WEB模块当然必须要引入WEB模块的依赖
org.springframework.boot spring-boot-starter-web
我们需要编写一个SpringBoot启动类,SpringbootFirstExperienceApplication.java
@SpringBootApplication
publicclassSpringbootFirstExperienceApplication{
publicstaticvoidmain(String[]args){
SpringApplication.run(SpringbootFirstExperienceApplication.class,args);
}
}
到了这里我们直接把他当成SpringMVC来使用就行了,不过这里默认是不支持JSP官方推荐使用模板引擎,后面会写到整合JSP。这里我就不写Controller了。
@SpringBootApplication:之前用户使用的是3个注解注解他们的main类。分别是@Configuration,@EnableAutoConfiguration,@ComponentScan。由于这些注解一般都是一起使用,springboot提供了一个统一的注解@SpringBootApplication。
注意事项:我们使用这个注解在不指定扫描路径的情况下,SpringBoot只能扫描到和SpringbootFirstExperienceApplication同包或子包的Bean;
SpringBoot目录结构#
在src/main/resources中我们可以有几个文件夹:
templates:用来存储模板引擎的,Thymeleaf,FreeMarker,Velocity等都是不错的选择。
static:存储一些静态资源,css,js等
public:在默认SpringBoot工程中是不生成这个文件夹的,但是在自动配置中我们可以有这个文件夹用来存放公共的资源(html等)
application.properties:这个文件名字是固定的,SpringBoot启动会默认加载这些配置在这里面可以配置端口号,访问路径,数据库连接信息等等。这个文件非常重要,当然官方中推出了一个yml格式这是非常强大的数据格式。
整合JdbcTemplate#
引入依赖:
org.springframework.boot spring-boot-starter-parent 1.5.2.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-jdbc mysql mysql-connector-java org.springframework.boot spring-boot-starter-test test
配置application.properties,虽然说是“零配置”但是这些必要的肯定要指定,否则它怎么知道连那个数据库?
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver
使用方式:
@Service
publicclassEmployeeService{
@Autowired
privateJdbcTemplatejdbcTemplate;
publicbooleansaveEmp(Stringname,Stringemail,Stringgender){
Stringsql="insertintotal_employeevalues(null,?,?,?)";
intresult=jdbcTemplate.update(sql,name,email,gender);
System.out.println("result:"+result);
returnresult>0?true:false;
}
}
@RestController
publicclassEmployeeController{
@Autowired
privateEmployeeServiceemployeeService;
@RequestMapping("/save")
publicStringinsert(Stringname,Stringemail,Stringgender){
booleanresult=employeeService.saveEmp(name,email,gender);
if(result){
return"success";
}
return"error";
}
}
这里我们直接返回一个文本格式。
@RestController#
在上面的代码中我们使用到这个注解修改我们的Controller类而是不使用@Controller这个注解,其实中包含了@Controller,同时包含@ResponseBody既然修饰在类上面那么就是表示这个类中所有的方法都是@ResponseBody所以在这里我们返回字符串在前台我们会以文本格式展示,如果是对象那么它会自动转换成json格式返回。
整合JSP#
在创建整合JSP的时候指定要选WAR,一定要选WAR。
引入依赖:
org.springframework.boot spring-boot-starter-parent 1.5.2.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-tomcat org.apache.tomcat.embed tomcat-embed-jasper
然后我们只需要配置试图解析器路径就可以了。
#配置试图解析器前缀 spring.mvc.view.prefix=/WEB-INF/views/ #配置试图解析器后缀 spring.mvc.view.suffix=.jsp
整合JPA#
同样的整合JPA我们只需要启动我们SpringBoot已经集成好的模块即可。
添加依赖:
org.springframework.boot spring-boot-starter-parent 1.5.2.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-test test mysql mysql-connector-java
启动JPA组件后直接配置数据库连接信息就可以使用JPA功能。
Application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver
实体类:Employee.java
@Table(name="tal_employee")
@Entity
publicclassEmployeeimplementsSerializable{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
privateIntegerid;
@Column(name="last_Name")
privateStringlastName;
privateStringemail;
privateStringgender;
//getset省略
}
EmployeeDao接口:
publicinterfaceEmployeeDaoextendsJpaRepository{ }
EmployeeController.java:
@Controller
publicclassEmployeeController{
@Autowired
privateEmployeeDaoemployeeDao;
@ResponseBody
@RequestMapping("/emps")
publicListgetEmployees(){
Listemployees=employeeDao.findAll();
System.out.println(employees);
returnemployees;
}
}
整合MyBatis#
引入依赖:
org.springframework.boot spring-boot-starter-parent 1.5.2.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-jdbc org.springframework.boot spring-boot-starter-logging org.mybatis.spring.boot mybatis-spring-boot-starter 1.2.2 org.springframework.boot spring-boot-starter-test test mysql mysql-connector-java
配置application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver ##############datasourceclasspath数据连接池地址############## #spring.datasource.type=com.alibaba.druid.pool.DruidDataSource #指定我们的mapper.xml位置 mybatis.mapper-locations=classpath:com/simple/springboot/mybatis/dao/mapper/*.xml #entity.class指定我们实体类所在包位置 mybatis.type-aliases-package=com.simple.springboot.mybatis.entity
当然这里还有很多属性如果想要使用可以参考官方文档。到了这里其他就不写了,把他当作SSM使用就ok。
注意事项:在我们的Dao层接口中一定要在类上加上注解@Mapper否则无法扫描到。
AOP功能使用#
在我们SpringBoot中使用AOP非常简单。
packagecom.simple.springboot.aop;
importorg.aspectj.lang.ProceedingJoinPoint;
importorg.aspectj.lang.annotation.After;
importorg.aspectj.lang.annotation.AfterThrowing;
importorg.aspectj.lang.annotation.Around;
importorg.aspectj.lang.annotation.Aspect;
importorg.aspectj.lang.annotation.Before;
importorg.aspectj.lang.annotation.Pointcut;
importorg.springframework.stereotype.Component;
@Aspect
@Component
publicclassSpringBootAspect{
/**
*定义一个切入点
*@author:SimpleWu
*@Date:2018年10月12日
*/
@Pointcut(value="execution(*com.simple.springboot.util.*.*(..))")
publicvoidaop(){}
/**
*定义一个前置通知
*@author:SimpleWu
*@Date:2018年10月12日
*/
@Before("aop()")
publicvoidaopBefore(){
System.out.println("前置通知SpringBootAspect....aopBefore");
}
/**
*定义一个后置通知
*@author:SimpleWu
*@Date:2018年10月12日
*/
@After("aop()")
publicvoidaopAfter(){
System.out.println("后置通知SpringBootAspect....aopAfter");
}
/**
*处理未处理的JAVA异常
*@author:SimpleWu
*@Date:2018年10月12日
*/
@AfterThrowing(pointcut="aop()",throwing="e")
publicvoidexception(Exceptione){
System.out.println("异常通知SpringBootAspect...exception.."+e);
}
/**
*环绕通知
*@author:SimpleWu
*@throwsThrowable
*@Date:2018年10月12日
*/
@Around("aop()")
publicvoidaround(ProceedingJoinPointinvocation)throwsThrowable{
System.out.println("SpringBootAspect..环绕通知Before");
invocation.proceed();
System.out.println("SpringBootAspect..环绕通知After");
}
}
任务调度#
SpringBoot已经集成好一个调度功能。
@Component
publicclassScheduledTasks{
privatestaticfinalSimpleDateFormatdateFormat=newSimpleDateFormat("HH:mm:ss");
/**
*任务调度,每隔5秒执行一次
*@author:SimpleWu
*@Date:2018年10月12日
*/
@Scheduled(fixedRate=1000)
publicvoidreportCurrentTime(){
System.out.println("现在时间:"+dateFormat.format(newDate()));
}
}
然后启动的时候我们必须要在主函数类上加上注解:@EnableScheduling(翻译过来就是开启调度)
/**
*SpringBoot使用任务调度
*@EnableScheduling标注程序开启任务调度
*@author:SimpleWu
*@Date:2018年10月12日
*/
@SpringBootApplication
@EnableScheduling
publicclassApp{
publicstaticvoidmain(String[]args){
SpringApplication.run(App.class,args);
}
}
整合RabbitMq#
安装RabbitMq
由于RabbitMQ依赖Erlang,所以需要先安装Erlang。
sudoyuminstall-ymakegccgcc-c++m4opensslopenssl-develncurses-develunixODBCunixODBC-develjavajava-devel sudoyuminstallepel-release sudoyuminstallerlang sudoyuminstallsocat
下载RabbitMQ,并且安装
sudowgethttp://www.rabbitmq.com/releases/rabbitmq-server/v3.6.15/rabbitmq-server-3.6.15-1.el7.noarch.rpm sudoyuminstallrabbitmq-server-3.6.15-1.el7.noarch.rpm
进入cd/etc/rabbitmq/创建vimrabbitmq.config
[{rabbit,[{loopback_users,[]}]}].
这里的意思是开放使用,rabbitmq默认创建的用户guest,密码也是guest,这个用户默认只能是本机访问,localhost或者127.0.0.1,从外部访问需要添加上面的配置。如果没有找到清除日志
rmrabbit\@rabbit@localhost-sasl.log
最好还是直接sudorabbitmqctlset_user_tagsrootadministrator,给root用户赋值管理员权限
RabbitMQ,基本操作
#添加开机启动RabbitMQ服务 systemctlenablerabbitmq-server.service #查看服务状态 systemctlstatusrabbitmq-server.service #启动服务 systemctlstartrabbitmq-server.service #停止服务 systemctlstoprabbitmq-server.service #查看当前所有用户 rabbitmqctllist_users #查看默认guest用户的权限 rabbitmqctllist_user_permissionsguest #由于RabbitMQ默认的账号用户名和密码都是guest。为了安全起见,先删掉默认用户 rabbitmqctldelete_userguest #添加新用户 rabbitmqctladd_userusernamepassword #设置用户tag rabbitmqctlset_user_tagsusernameadministrator #赋予用户默认vhost的全部操作权限 rabbitmqctlset_permissions-p/username".*"".*"".*" #查看用户的权限 rabbitmqctllist_user_permissionsusername
如果只从命令行操作RabbitMQ,多少有点不方便。幸好RabbitMQ自带了web管理界面,只需要启动插件便可以使用。
rabbitmq-pluginsenablerabbitmq_management
访问:http://服务器IP:15672
整合RabbitMq
导入Maven依赖
org.springframework.boot spring-boot-starter-parent 2.1.4.RELEASE 1.8 org.springframework.boot spring-boot-starter-amqp org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test
设置application.properties配置文件
spring.application.name=springboot-rabbitmq #RabbitMq所在服务器IP spring.rabbitmq.host=192.168.197.133 #连接端口号 spring.rabbitmq.port=5672 #用户名 spring.rabbitmq.username=root #用户密码 spring.rabbitmq.password=123456 #开启发送确认 spring.rabbitmq.publisher-confirms=true #开启发送失败退回 spring.rabbitmq.publisher-returns=true spring.rabbitmq.virtual-host=/
创建RabbitMq队列初始化类,初始化队列
/**
*@authorSimpleWu
*@Date2019-05-17
*该类初始化队列
*/
@Configuration
publicclassRabbitMqInitialization{
/**
*创建队列队列名字为SayQueue
*@return
*/
@Bean
publicQueueSayQueue(){
returnnewQueue("SayQueue");
}
}
创建生产者
/**
*@authorSimpleWu
*@Date2019-05-17
*生产者
*/
@Component
publicclassSayProducer{
@Autowired
privateRabbitTemplaterabbitTemplate;
publicvoidsend(Stringname){
StringsendMsg="hello:"+name+""+newDate();
//指定队列
this.rabbitTemplate.convertAndSend("SayQueue",sendMsg);
}
}
创建消费者
@RabbitListener:当监听到队列SayQueue中有消息时则会进行接收并处理
@RabbitHandler:标注在类上面表示当有收到消息的时候,就交给@RabbitHandler的方法处理,具体使用哪个方法处理,根据MessageConverter转换后的参数类型
/**
*@authorSimpleWu
*@Date2019-05-17
*消费者
*queues指定监听的队列
*/
@Component
@RabbitListener(queues="SayQueue")
publicclassSayConsumer{
@RabbitHandler
publicvoidprocess(Stringhello){
System.out.println("SayConsumer:"+hello);
}
}
创建接口进行测试
@RestController
publicclassSayController{
@Autowired
privateSayProducersayProducer;
@RequestMapping("/send/{name}")
publicStringsend(@PathVariableStringname){
sayProducer.send(name);
return"SendSucccessSimpleWu";
}
}
启动类就用IDEA默认生成的就好了。
http://10.192.132.22:8080/send/First发送请求
消费者接受消息:SayConsumer:hello:FirstTueMay0717:57:02CST2019
注:在传输对象时一定要序列化
整合邮件发送#
导入依赖
org.springframework.boot spring-boot-starter-mail
配置Properties文件
#根据类型配置 spring.mail.host=smtp.qq.com spring.mail.port=465 spring.mail.username=450255266@qq.com #对于qq邮箱而言密码指的就是发送方的授权码 spring.mail.password=看不见我-0- spring.mail.protocol=smtp spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.ssl.enable=true spring.mail.default-encoding=UTF-8 #是否用启用加密传送的协议验证项 #注意:在spring.mail.password处的值是需要在邮箱设置里面生成的授权码,这个不是真实的密码。
spring.mail.host需要根据不同的邮箱类型配置不同的服务器地址
发送邮箱
/**
*@authorSimpleWu
*@data2019=05-17
*发送邮件
*/
@Component
publicclassEmailService{
@Autowired
privateJavaMailSenderjavaMailSender;
publicvoidsendSimpleMail(){
MimeMessagemessage=null;
try{
message=javaMailSender.createMimeMessage();
MimeMessageHelperhelper=newMimeMessageHelper(message,true);
helper.setFrom("450255266@qq.com");
helper.setTo("450255266@qq.com");
helper.setSubject("标题:发送Html内容");
StringBuffercontext=newStringBuffer();
context.append("");
context.append("HelloSpringBootEmailStartSimpleWu!!");
context.append("");
helper.setText(context.toString(),true);//设置true发送html邮件
//带附件
//FileSystemResourcefileSystemResource=newFileSystemResource(newFile("D:\2019-05-07.pdf"));
//helper.addAttachment("邮箱附件",fileSystemResource);
javaMailSender.send(message);
}catch(MessagingExceptione){
e.printStackTrace();
}
}
}
注:最好使用异步接口发送邮件,并且发送邮件的服务器为单独部署。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。