Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Starter in Spring Boot

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to use Starter in Spring Boot". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let the editor take you to learn how to use Starter in Spring Boot.

Introduction to SpringBoot

Spring Boot is a new framework provided by the Pivotal team, which is designed to simplify the initial building and development process of new Spring applications. The framework is configured in a specific way so that developers no longer need to define a templated configuration. In this way, Boot is committed to becoming a leader in the booming field of rapid application development (rapid application development).

Spring Boot makes our Spring application lighter. For example, you can just rely on a Java class to run a Spring reference. You can also package your application as jar and run your Spring Web application by using java-jar.

The main advantages of Spring Boot are:

1. Get started faster for all Spring developers

2. Out of the box, various default configurations are provided to simplify project configuration.

3. Embedded container simplifies Web project

4. No requirements for redundant code generation and XML configuration

As long as there is a certain foundation in the following code, you will find that this code example is very simple and almost "zero configuration" for developers.

SpringBoot operation

Development tools: jdk8,IDEA,STS,eclipse (need to install the STS plug-in) these all support the quick start of the SpringBoot project. I won't start it quickly here, use the maven project. The first thing to learn any technology is to be proficient in HelloWord, so let's have a first experience.

First of all, just use maven to create the maven project we created directly in the form of a jar package. First, let's introduce the dependency of SpringBoot.

First of all, we need to rely on the SpringBoot parent project, which is necessary in every project.

Org.springframework.boot spring-boot-starter-parent 2.0.5.RELEASE UTF-8 UTF-8 1.8

Of course, when we start the WEB module, we have to introduce the dependency of the WEB module.

Org.springframework.boot spring-boot-starter-web

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);}}

At this point, we can just use it as SpringMVC, but by default, we do not support the official recommendation of JSP to use template engine, which will be written later on to integrate JSP. I won't write Controller here.

SpringBootApplication: previously, users used three main classes that annotated them. They are @ Configuration,@EnableAutoConfiguration,@ComponentScan. Because these annotations are generally used together, spring boot provides a unified annotation @ SpringBootApplication.

Note: using this note, SpringBoot can only scan Bean of the same package or subpackage as SpringbootFirstExperienceApplication without specifying the scanning path.

SpringBoot directory structure

SpringBoot directory structure # We can have several folders in src/main/resources:

Templates: used to store template engine, Thymeleaf,FreeMarker,Velocity and so on are good choices.

Static: store some static resources, css,js, etc.

Public: this folder is not generated in the default SpringBoot project, but in automatic configuration we can have this folder to store public resources (html, etc.)

Application.properties: the name of this file is fixed, and the SpringBoot startup loads these configurations by default, where you can configure port numbers, access paths, database connection information, and so on. This document is very important, and of course there is an official yml format, which is a very powerful data format.

Integrate JdbcTemplate

Introduce dependencies:

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

Configure application.properties, although it is said to be "zero configuration", but 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

Mode of use:

@ 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 email,String gender) {boolean result = employeeService.saveEmp (name, email, 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 using @ Controller, which actually includes @ Controller and @ ResponseBody. Since it is decorated on the class, it means that all the methods in this class are @ ResponseBody, so here we return the string in the foreground and show it in text format. If it is an object, it will be automatically converted to json format and returned.

Integrate JSP

When creating an integrated JSP, specify that you want to select WAR and be sure to select WAR.

Introduce dependencies:

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

Then we just need to configure the path to the attempted parser.

# configure attempt parser prefix spring.mvc.view.prefix=/WEB-INF/views/ # configure attempt parser suffix spring.mvc.view.suffix=.jsp

Integrate JPA

For the same integration of JPA, we only need to start the modules that have been integrated by our SpringBoot.

Add dependencies:

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

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 ellipsis}

EmployeeDao interface:

Public interface EmployeeDao extends JpaRepository {}

EmployeeController.java:

@ Controller public class EmployeeController {@ Autowired private EmployeeDao employeeDao; @ ResponseBody @ RequestMapping ("/ emps") public List getEmployees () {List employees = employeeDao.findAll (); System.out.println (employees); return employees;}}

Integrate MyBatis

Introduce dependencies:

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

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 data connection Pool address # # spring.datasource.type=com.alibaba.druid.pool.DruidDataSource # specify our mapper.xml location mybatis.mapper-locations=classpath:com/simple/springboot/mybatis/ Dao/mapper/*.xml # entity.class specifies the package location mybatis.type-aliases-package=com.simple.springboot.mybatis.entity where our entity class resides

Of course, there are many properties here that you can refer to the official documentation if you want to use them. If you don't write anything else here, use it as a SSM and use it as an ok.

Note: be sure to annotate the class with @ Mapper in our Dao layer interface or it won't be scanned.

Use of AOP function

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 {/ * define a pointcut * @ author:SimpleWu * @ Date: October 12, 2018 * / @ Pointcut (value= "execution (* com.simple.springboot.util.*.* (..)") Public void aop () {} / * define a pre-notification * @ author:SimpleWu * @ Date: October 12, 2018 * / @ Before ("aop ()") public void aopBefore () {System.out.println ("pre-notification SpringBootAspect....aopBefore") } / * define a post notification * @ author:SimpleWu * @ Date: October 12, 2018 * / @ After ("aop ()") public void aopAfter () {System.out.println ("post notification SpringBootAspect....aopAfter") } / * handle unhandled JAVA exceptions * @ author:SimpleWu * @ Date: October 12, 2018 * / @ AfterThrowing (pointcut= "aop ()", throwing= "e") public void exception (Exception e) {System.out.println ("exception notification SpringBootAspect...exception." + e) } / * author:SimpleWu * @ throws Throwable * @ Date: October 12, 2018 * / @ Around ("aop ()") public void around (ProceedingJoinPoint invocation) throws Throwable {System.out.println ("SpringBootAspect..") Surround notification Before "); invocation.proceed (); System.out.println (" SpringBootAspect.. " Notify After around ");}}

Task scheduling

SpringBoot has integrated a scheduling function.

@ Component public class ScheduledTasks {private static final SimpleDateFormat dateFormat = new SimpleDateFormat ("HH:mm:ss"); / * Task scheduling is performed every 5 seconds * @ author:SimpleWu * @ Date: October 12, 2018 * / @ Scheduled (fixedRate = 1000) public void reportCurrentTime () {System.out.println ("now time:" + dateFormat.format (new Date ();}}

Then when starting, we have to add a note to the main function class: @ EnableScheduling (translation means to enable scheduling)

/ * * SpringBoot uses the task scheduling program * @ EnableScheduling to enable task scheduling * @ author: SimpleWu * @ Date: October 12, 2018 * / @ SpringBootApplication @ EnableScheduling public class App {public static void main (String [] args) {SpringApplication.run (App.class, args);}}

Integrate RabbitMq

Install RabbitMq because RabbitMQ depends on Erlang, so 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

Enter cd / etc/rabbitmq/ to create vim rabbitmq.config

[{rabbit, [{loopback_users, []}]}].

This means open use. The user created by rabbitmq by default is guest, and 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 cleanup log is not found

Rm rabbit\ @ rabbit@localhost-sasl.log

It is best to directly sudo rabbitmqctl set_user_tags root administrator, assign administrator privileges to root users, RabbitMQ, basic operation

# add boot RabbitMQ service systemctl enable rabbitmq-server.service # View service status systemctl status rabbitmq-server.service # start service systemctl start rabbitmq-server.service # stop service systemctl stop rabbitmq-server.service # View all current users rabbitmqctl list_users # View the permissions of the default guest user rabbitmqctl list_user_permissions guest # because the default account username and password of RabbitMQ are guest. For the sake of security, delete the default user rabbitmqctl delete_user guest # add a new user rabbitmqctl add_user username password # set the user tag rabbitmqctl set_user_tags username administrator # give the user all operation rights of the default vhost rabbitmqctl set_permissions-p / username ". *" # View the user's permission rabbitmqctl list_user_permissions username

If you only operate RabbitMQ from the command line, it is somewhat inconvenient. Fortunately, RabbitMQ has its own web management interface, which can be used only by launching the plug-in.

Rabbitmq-plugins enable rabbitmq_management

Access: http:// server IP:15672

Integrate RabbitMq

Import Maven dependencies

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

Set up the application.properties profile

Spring.application.name=springboot-rabbitmq # RabbitMq server IP spring.rabbitmq.host=192.168.197.133 # connection port number spring.rabbitmq.port=5672 # username spring.rabbitmq.username=root # user password spring.rabbitmq.password=123456 # enable send confirmation spring.rabbitmq.publisher-confirms=true # enable send failed return 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 * this class initializes the queue * / @ Configuration public class RabbitMqInitialization {/ * create the queue name as SayQueue * @ return * / @ Bean public Queue SayQueue () {return new Queue ("SayQueue");}}

Create a producer

/ * @ author SimpleWu * @ Date 2019-05-17 * producer * / @ Component public class SayProducer {@ Autowired private RabbitTemplate rabbitTemplate; public void send (String name) {String sendMsg = "hello:" + name + "" + new Date (); / / specify queue this.rabbitTemplate.convertAndSend ("SayQueue", sendMsg);}}

Create consumer @ RabbitListener: when you hear a message in queue SayQueue, it will receive and process @ RabbitHandler: marked on the class to indicate that when a message is received, it will be handed over to the @ RabbitHandler method. Which method will be used to handle it, according to the parameter type after MessageConverter conversion?

/ * @ author SimpleWu * @ Date 2019-05-17 * Consumer * queue specified by queues * / @ Component @ RabbitListener (queues = "SayQueue") public class SayConsumer {@ RabbitHandler public void process (String hello) {System.out.println ("SayConsumer:" + hello);}}

Create an interface 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";}}

It would be nice to start the class with IDEA generated by default. Http://10.192.132.22:8080/send/First sends a message requesting consumer acceptance: SayConsumer: hello: First Tue May 07 17:57:02 CST 2019 Note: be sure to serialize when transferring objects

Integrated email delivery

Import dependency

Org.springframework.boot spring-boot-starter-mail

Configure the Properties file

# configure spring.mail.host=smtp.qq.com spring.mail.port=465 spring.mail.username=450255266@qq.com according to type # for QQ Mail, password means that the sender's authorization code spring.mail.password= cannot see me-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 # whether to use a protocol that enables encrypted transmission Verification item # Note: the value at spring.mail.password is the authorization code that needs to be generated in the mailbox settings. This is not a real password.

Spring.mail.host needs to configure different server addresses to send mailboxes according to different mailbox types.

/ * * @ author SimpleWu * @ data 2019 05-17 * send email * / @ 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 ("title: send Html content"); StringBuffer context = new StringBuffer (); context.append (""); context.append ("Hello SpringBoot Email Start simplicity!"); context.append ("

"); helper.setText (context.toString (), true); / / set true to send html email / / with attachments / / FileSystemResource fileSystemResource=new FileSystemResource (new File (" D:\ 2019-05-07.pdf ")); / / helper.addAttachment (" mailbox attachments ", fileSystemResource); javaMailSender.send (message) } catch (MessagingException e) {e.printStackTrace ();}

Note: it is best to use the asynchronous interface to send mail, and the server that sends the mail is deployed separately.

At this point, I believe you have a deeper understanding of "how to use Starter in Spring Boot". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report