2-hour Learning Spring Boot

Source: Internet
Author: User
Tags spring initializr

I. What is Spring Boot

Takes an opinionated view of building Production-ready Spring applications. Spring Boot Favors convention over-configuration and is designed-to get-up and running as quickly as possible.

--Excerpt from official website

Translation: The idea of building a production-ready Spring application was adopted. The Spring boot habit takes precedence over the configured conventions and is designed to get you up and running as soon as possible.

Spring Boot is dedicated to simplicity, allowing developers to write fewer configurations and programs to run and start faster. It is the next generation Javaweb framework, and it is the foundation of Spring Cloud (microservices).

Second, build the first Spring Boot program

Projects can be built on Start.spring.io, or built with idea. This case uses idea.

Specific steps:

new prpject -> spring initializr ->{name :firstspringboot , type: mavenproject,packaging:jar ,..}  ->{spring version :1.5.2  web: web } -> ....

When the app is created successfully, the appropriate directories and files are generated.

There is a application class, which is the entry for the program:

@SpringBootApplicationpublic class FirstspringbootApplication {    public static void main(String[] args) {        SpringApplication.run(FirstspringbootApplication.class, args);    }}

Under the resources file, under another Application.yml file, it is the configuration file for the program. The default is empty, the write point configuration, the program port is 8080,context-path to/springboot:

server:  port: 8080  context-path: /springboot

Write a Hellocontroller:

@RestController     //等同于同时加上了@Controller和@ResponseBodypublic class HelloController {    //访问/hello或者/hi任何一个地址,都会返回一样的结果    @RequestMapping(value = {"/hello","/hi"},method = RequestMethod.GET)    public String say(){        return "hi you!!!";    }}

Run application main (), the program will start, because the Spring boot automatically built the servlet container, so do not need a similar traditional way, first deploy to the container and then start the container. Only need to run main (), then open the browser input URL: Localhost:8080/springboot/hi, you can see in the browser: hi you!!!

Three. Property configuration

To add a property to a appliction.yml file:

server:  port: 8080  context-path: /springbootgirl:  name: B  age: 18  content: content:${name},age:${age}

In the Java file, get the Name property, as follows:

@Value("${name}") private String name;

You can also use configurationproperties annotations to inject attributes into the bean and annotate the bean into the spring container with Component annotations:

@ConfigurationProperties(prefix="girl")@Componentpublic class GirlProperties {    private String name;    private int age;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }}

In addition, the configuration file can be used to create a different environment of the configuration text, see Code:

spring:  profiles:    active: prod
Four. Working with the database in JPA mode

Import the jar and add dependencies in Pom.xml:

<dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-jpa</artifactId>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>        </dependency>

To add a database configuration in APPILICATION.YML:

spring:  profiles:    active: prod  datasource:    driver-class-name: com.mysql.jdbc.Driver    url: jdbc:mysql://localhost:3306/dbgirl?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8    username: root    password: root  jpa:    hibernate:      ddl-auto: create    show-sql: true

These are some of the common configuration of the database there is nothing to say, where ddl_auto:create represents the creation of tables in the database, update represents updates, the first boot needs create, if you want to create a table of the database through hibernate annotations, then you need to change Update.

Create an entity girl, which is hibernate-based:

@Entitypublic class Girl {    @Id    @GeneratedValue    private Integer id;    private String cupSize;    private Integer age;    public Girl() {    }    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }    public String getCupSize() {        return cupSize;    }    public void setCupSize(String cupSize) {        this.cupSize = cupSize;    }}

To create the Dao interface, Springboot will automatically annotate the interface class into the spring container, without me doing any configuration, just inherit the jparepository:

// 其中第二个参数为Id的类型public interface GirlRep extends JpaRepository<Girl,Integer>{   }

Create a Girlcontroller, write an API to get all the girl and add Girl APIs, run it yourself:

@RestControllerpublic class GirlController {    @Autowired    private GirlRep girlRep;    /**     * 查询所有女生列表     * @return     */    @RequestMapping(value = "/girls",method = RequestMethod.GET)    public List<Girl> getGirlList(){        return girlRep.findAll();    }    /**     * 添加一个女生     * @param cupSize     * @param age     * @return     */    @RequestMapping(value = "/girls",method = RequestMethod.POST)    public Girl addGirl(@RequestParam("cupSize") String cupSize,                        @RequestParam("age") Integer age){        Girl girl = new Girl();        girl.setAge(age);        girl.setCupSize(cupSize);        return girlRep.save(girl);    }   

If you need a transaction, add @Transaction annotations to the service layer.

2-hour Learning Spring Boot

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.