Spring Boot Part 25: Learn springboot in 2 hours

1. 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 you up and running as quickly as possible.

Taken from the official website

Translation: Adopted the point of view of building production-ready Spring applications. Spring Boot takes precedence over configuration conventions and aims to get you up and running as quickly as possible.

Spring boot is committed to simplicity, allowing developers to write less configuration, and the program can run and start faster. It is the next generation java web framework and it is the foundation of spring cloud (microservices).

Second, build the first sping boot program

You can build projects on start.spring.io, or you can build with ideas. This case uses idea.

Specific steps:

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

After the application is created successfully, the corresponding directories and files will be generated.

There is an Application class, which is the entry point of the program:

@SpringBootApplication
public class FirstspringbootApplication {

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

There is another application.yml file under the resources file, which is the configuration file of the program. The default is empty, write point configuration, the port of the program is 8080, and the context-path is /springboot:

server:
  port: 8080
  context-path: /springboot

Write a HelloController:

@RestController     //等同于同时加上了@Controller和@ResponseBody
public class HelloController {

    //访问/hello或者/hi任何一个地址,都会返回一样的结果
    @RequestMapping(value = {"/hello","/hi"},method = RequestMethod.GET)
    public String say(){
        return "hi you!!!";
    }
}

Run the main() of the Application, and the rendering will start. Since springboot automatically has a built-in servlet container, there is no need to deploy it to the container first and then start the container in a traditional way. Just run main(), then open the browser and enter the URL: localhost:8080/springboot/hi, you can see on the browser: hi you!!!

3. Property configuration

Add properties in application.yml file:

server:
  port: 8080
  context-path: /springboot

girl:
  name: B
  age: 18
  content: content:${name},age:${age}

In the java file, get the name attribute as follows:

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

You can also inject properties into beans through ConfigurationProperties annotations, and annotate beans into spring containers through Component annotations:

@ConfigurationProperties(prefix="girl")
@Component
public 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, configuration files for different environments can be formulated through configuration files, see the source code for details:

spring:
  profiles:
    active: prod

4. Operate the database through jpa

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>

Add database configuration in application.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: 123

  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true

These are some common configurations of databases. There is nothing to say. ddl_auto: create represents creating a table in the database, and update represents updating. The first startup requires create. If you want to create a database table through hibernate annotation, you need to change it to update.

Create an entity girl, which is based on hibernate:

@Entity
public 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;
    }
}

Create the Dao interface, and springboot will automatically annotate the interface class into the spring container. I don't need to do any configuration, just inherit JpaRepository:

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

Create a GirlController, write an api to get all girls and an api to add girls, just run it yourself:

@RestController
public 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 a transaction is required, add the @Transaction annotation to the service layer. It's already early morning and I'm going to bed.

Source code; http://download.csdn.net/detail/forezp/9778235

Follow my column "The Simplest Spring Cloud Tutorial in History" http://blog.csdn.net/column/details/15197.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324602617&siteId=291194637