Detailed explanation of starter examples commonly used in spring boot Enterprises
Introduction to springboot#
Spring boot is a new framework provided by pivot team. It is designed to simplify the initial construction and development process of new spring applications. The framework uses a specific way to configure, so that developers no longer need to define templated configurations. In this way, boot is committed to becoming a leader in the booming field of rapid application development.
Spring boot makes our spring applications lighter. For example, you can rely on a Java class to run a spring reference. You can also package your application as a jar and run your spring web application by using java - jar.
Main advantages of spring boot:
In the following code, as long as there is a certain foundation, you will find that it is very simple to write code examples, which is almost "zero configuration" for developers.
Springboot run#
Development tools: jdk8, idea, STS, eclipse (STS plug-in needs to be installed) all support the quick start of springboot project. I won't use the quick start here and use Maven project. To learn any technology, we must first master helloword. Let's have a first experience.
First, just use Maven to create the Maven project directly in the form of jar package. First, let's introduce the dependency of springboot
First, we need to rely on the springboot parent project, which is necessary in every project.
<!--引入SpringBoot父依赖--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.5.RELEASE</version> <relativePath/> </parent> <!--编码与JAVA版本--> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties>
When we start the web module, of course, we must introduce the dependency of the web module
<dependencies> <!--引入SpringBoot-WEB模块--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
We need to write a springboot startup class, springbootfirstexperienceapplication java
@SpringBootApplication public class SpringbootFirstExperienceApplication { public static void main(String[] args) { SpringApplication.run(SpringbootFirstExperienceApplication.class,args); } }
Here, we can directly use it as spring MVC, but it does not support JSP by default. The official recommends using the template engine, which will be written about integrating JSP later. I won't write here.
@Spring boot application: previously, users used three annotations to annotate their main class. They are @ configuration, @ enableautoconfiguration, @ componentscan. Since these annotations are generally used together, spring boot provides a unified annotation @ springbootapplication.
Note: we use this annotation. Without specifying the scanning path, springboot can only scan beans in the same package or sub package as springbootfirstexperienceapplication;
Springboot directory structure#
In Src / main / resources, we can have several folders:
Templates: used to store template engines. Thymeleaf, FreeMarker, velocity, etc. are good choices.
Static: store some static resources, CSS, JS, etc
Public: this folder is not generated in the default springboot project, but we can have this folder to store public resources (HTML, etc.) in automatic configuration
application. Properties: the file name is fixed. Springboot will load these configurations by default. You can configure port number, access path, database connection information, etc. This file is very important. Of course, the official has launched a YML format, which is a very powerful data format.
Integrate jdbctemplate#
Import dependency:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <dependencies> <!--引入WEB模块--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--引入JDBC模块--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--引入数据库驱动--> <dependency> <groupId>MysqL</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
Configure application Properties, although it is said to be "zero configuration", these necessary must be specified. Otherwise, how does it know to connect to that database?
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
Usage:
@Service public class EmployeeService { @Autowired private JdbcTemplate jdbcTemplate; public boolean saveEmp(String name,String email,String gender){ String sql = "insert into tal_employee values(null,?,?)"; int result = jdbcTemplate.update(sql,name,email,gender); System.out.println("result : " + result); return result > 0 ? true:false; } }
@RestController public class EmployeeController { @Autowired private EmployeeService employeeService; @RequestMapping("/save") public String insert(String name,String gender){ boolean result = employeeService.saveEmp(name,gender); if(result){ return "success"; } return "error"; } }
Here we return a text format directly.
@RestController#
In the above code, we use this annotation to modify our controller class instead of @ controller. In fact, it contains @ controller and @ ResponseBody. Since it is modified on the class, it means that all methods in this class are @ ResponseBody. Therefore, here we return the string, which will be displayed in text format on the foreground, If it is an object, it will be automatically converted to JSON format and returned.
Integrate JSP#
When creating an integrated JSP, you must select war.
Import dependency:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <dependencies> <!-- SpringBoot WEB组件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 整合JSP依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> </dependencies>
Then we just need to configure the parser path.
#配置试图解析器前缀 spring.mvc.view.prefix=/WEB-INF/views/ #配置试图解析器后缀 spring.mvc.view.suffix=.jsp
Integrate JPA#
Similarly, to integrate JPA, we only need to start the integrated module of springboot.
Add dependency:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--启动JPA组件--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>MysqL</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies>
After starting the JPA component, you can directly configure the database connection information to use the JPA function.
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
Entity class: employee java
@Table(name="tal_employee") @Entity public class Employee implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column(name="last_Name") private String lastName; private String email; private String gender; //get set 省略 }
Employeedao interface:
public interface EmployeeDao extends JpaRepository<Employee,Integer>{ }
EmployeeController. java:
@Controller public class EmployeeController { @Autowired private EmployeeDao employeeDao; @ResponseBody @RequestMapping("/emps") public List<Employee> getEmployees(){ List<Employee> employees = employeeDao.findAll(); System.out.println(employees); return employees; } }
Integrate mybatis#
Import dependency:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--引入对JDBC的支持--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--引入对logging的支持--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </dependency> <!-- SpringBoot MyBatis启动器 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>MysqL</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies>
Configure 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 ##############datasource classpath 数据连接池地址############## #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
Of course, there are many properties here. If you want to use them, you can refer to the official documents. When you get here, don't write anything else. Just use it as SSM.
Note: in our Dao layer interface, we must add annotation @ mapper on the class, otherwise it cannot be scanned.
AOP function usage#
Using AOP in our springboot is very simple.
package com.simple.springboot.aop; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.pointcut; import org.springframework.stereotype.Component; @Aspect @Component public class SpringBootAspect { /** * 定义一个切入点 * @author:SimpleWu * @Date:2018年10月12日 */ @pointcut(value="execution(* com.simple.springboot.util.*.*(..))") public void aop(){} /** * 定义一个前置通知 * @author:SimpleWu * @Date:2018年10月12日 */ @Before("aop()") public void aopBefore(){ System.out.println("前置通知 SpringBootAspect....aopBefore"); } /** * 定义一个后置通知 * @author:SimpleWu * @Date:2018年10月12日 */ @After("aop()") public void aopAfter(){ System.out.println("后置通知 SpringBootAspect....aopAfter"); } /** * 处理未处理的JAVA异常 * @author:SimpleWu * @Date:2018年10月12日 */ @AfterThrowing(pointcut="aop()",throwing="e") public void exception(Exception e){ System.out.println("异常通知 SpringBootAspect...exception .." + e); } /** * 环绕通知 * @author:SimpleWu * @throws Throwable * @Date:2018年10月12日 */ @Around("aop()") public void around(ProceedingJoinPoint invocation) throws Throwable{ System.out.println("SpringBootAspect..环绕通知 Before"); invocation.proceed(); System.out.println("SpringBootAspect..环绕通知 After"); } }
Task scheduling#
Springboot has integrated a scheduling function.
@Component public class ScheduledTasks { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); /** * 任务调度,每隔5秒执行一次 * @author:SimpleWu * @Date:2018年10月12日 */ @Scheduled(fixedRate = 1000) public void reportCurrentTime() { System.out.println("现在时间:" + dateFormat.format(new Date())); } }
Then, when starting, we must add comments on the main function class: @ enableshcheduling (translated as enabling scheduling)
/** * SpringBoot使用任务调度 * @EnableScheduling标注程序开启任务调度 * @author :SimpleWu * @Date:2018年10月12日 */ @SpringBootApplication @EnableScheduling public class App { public static void main(String[] args) { SpringApplication.run(App.class,args); } }
Integrate rabbitmq#
Installing rabbitmq
Since rabbitmq depends on Erlang, you need to install Erlang first.
sudo yum install -y make gcc gcc-c++ m4 openssl openssl-devel ncurses-devel unixODBC unixODBC-devel java java-devel sudo yum install epel-release sudo yum install erlang sudo yum install socat
Download rabbitmq and install
sudo wget http://www.rabbitmq.com/releases/rabbitmq-server/v3.6.15/rabbitmq-server-3.6.15-1.el7.noarch.rpm sudo yum install rabbitmq-server-3.6.15-1.el7.noarch.rpm
Go to CD / etc / rabbitmq / to create VIM rabbitmq config
[{rabbit,[{loopback_users,[]}]}].
This means open use. Rabbitmq creates a guest by default. The password is also guest. By default, this user can only be accessed locally, localhost or 127.0 0.1, the above configuration needs to be added for external access. If the purge log is not found
rm rabbit\@rabbit@localhost-sasl.log
It is better to sudo rabbitmqctl set directly_ user_ Tags root administrator, assign administrator privileges to root user, rabbitmq, basic operations
# 添加开机启动RabbitMQ服务 systemctl enable rabbitmq-server.service # 查看服务状态 systemctl status rabbitmq-server.service # 启动服务 systemctl start rabbitmq-server.service # 停止服务 systemctl stop rabbitmq-server.service # 查看当前所有用户 rabbitmqctl list_users # 查看默认guest用户的权限 rabbitmqctl list_user_permissions guest # 由于RabbitMQ默认的账号用户名和密码都是guest。为了安全起见,先删掉默认用户 rabbitmqctl delete_user guest # 添加新用户 rabbitmqctl add_user username password # 设置用户tag rabbitmqctl set_user_tags username administrator # 赋予用户默认vhost的全部操作权限 rabbitmqctl set_permissions -p / username ".*" ".*" ".*" # 查看用户的权限 rabbitmqctl list_user_permissions username
It is somewhat inconvenient to operate rabbitmq only from the command line. Fortunately, rabbitmq comes with its own web management interface. You only need to start the plug-in to use it.
rabbitmq-plugins enable rabbitmq_management
Access: http: / / server IP: 15672
Integrate rabbitmq
Import Maven dependencies
<!--SpringBoot2.x--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <!--设置JAVA版本--> <properties> <java.version>1.8</java.version> </properties> <!--引入依赖--> <dependencies> <!--启动RabbitmQ--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> <!--启动WEB--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--启动TEST--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
Set application Properties configuration file
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=/
Create a rabbitmq queue initialization class to initialize the queue
/** * @author SimpleWu * @Date 2019-05-17 * 该类初始化队列 */ @Configuration public class RabbitMqInitialization { /** * 创建队列 队列名字为SayQueue * @return */ @Bean public Queue SayQueue() { return new Queue("SayQueue"); } }
Create producer
/** * @author SimpleWu * @Date 2019-05-17 * 生产者 */ @Component public class SayProducer { @Autowired private RabbitTemplate rabbitTemplate; public void send(String name){ String sendMsg = "hello: " + name + " " + new Date(); //指定队列 this.rabbitTemplate.convertAndSend("SayQueue",sendMsg); } }
Create consumer
@Rabbitlistener: when the supervisor hears a message in the sayqueue, it will receive and process it
@Rabbithandler: it is marked on the class to indicate the method to be handed over to @ rabbithandler for processing when a message is received. The specific method to be used for processing depends on the parameter type converted by messageconverter
/** * @author SimpleWu * @Date 2019-05-17 * 消费者 * queues 指定监听的队列 */ @Component @RabbitListener(queues = "SayQueue") public class SayConsumer { @RabbitHandler public void process(String hello) { System.out.println("SayConsumer : " + hello); } }
Create interfaces for testing
@RestController public class SayController { @Autowired private SayProducer sayProducer; @RequestMapping("/send/{name}") public String send(@PathVariable String name){ sayProducer.send(name); return "Send Succcess SimpleWu"; } }
Just start the class with the default generated by idea.
http://10.192.132.22:8080/send/First Send request
Consumer acceptance message: sayconsumer: Hello: first Tue may 07 17:57:02 CST 2019
Note: when transferring objects, you must serialize them
Integrated mail sending#
Import dependency
<!--启动邮箱发送依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
Configure properties file
#根据类型配置 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 needs to configure different server addresses according to different mailbox types
Send mailbox
/** * @author SimpleWu * @data 2019=05-17 * 发送邮件 */ @Component public class EmailService { @Autowired private JavaMailSender javaMailSender; public void sendSimpleMail(){ MimeMessage message = null; try { message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message,true); helper.setFrom("450255266@qq.com"); helper.setTo("450255266@qq.com"); helper.setSubject("标题:发送Html内容"); StringBuffer context = new StringBuffer(); context.append("<p style='color:red'>"); context.append("Hello SpringBoot Email Start SimpleWu!!"); context.append("</p>"); helper.setText(context.toString(),true);//设置true发送html邮件 //带附件 //FileSystemResource FileSystemResource=new FileSystemResource(new File("D:\2019-05-07.pdf")); //helper.addAttachment("邮箱附件",FileSystemResource); javaMailSender.send(message); } catch (MessagingException e) { e.printStackTrace(); } } }
Note: it is best to use asynchronous interface to send mail, and the server sending mail is deployed separately.
summary
The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. Thank you for your support.