Simple springboot example and springboot example

Source: Internet
Author: User
Tags spring initializr

Simple springboot example and springboot example

1. What is spring boot?

Takes an opinionated view of buildingproduction-ready Spring applications. Spring Boot favors convention overconfiguration and is designed to get you up and running as quickly as possible.

From official website

Translation: adopted the idea of building a production-ready Spring application. Spring Boot takes precedence over configuration practices and is designed to enable and run as soon as possible.

Springboot is committed to simplicity, allowing developers to write less configuration, and the program can run and start faster. It is the next-generation javaweb framework and is the basis of spring cloud (microservice.

2. Build the first sping boot program

You can create a project on start. spring. io or using idea. Idea is used in this case.

Procedure:

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

After the application is created, the corresponding directories and files are generated.

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

@SpringBootApplication
publicclass FirstspringbootApplication {
 
    publicstaticvoidmain(String[] args) {
        SpringApplication.run(FirstspringbootApplication.class, args);
    }
}

Another application. yml file under the resources file is the configuration file of the program. The default value is null. The write point is configured. The program port is 8080, and the context-path is/springboot:

server:
  port: 8080
  context-path: /springboot

Write a HelloController:

@RestController     // Equivalent to adding @ Controller and @ ResponseBody
publicclass HelloController {
 
    // Access/hello or/hi any address, the same result will be returned
    @RequestMapping(value = {"/hello","/hi"},method = RequestMethod.GET)
    public String say(){
        return"hi you!!!";
    }
}

Run main () of the Application, and the rendering starts. Because springboot automatically has a servlet container, you do not need to deploy it to the container and then start the container in a traditional way. You only need to run main (). Open the browser and enter the URL: localhost: 8080/springboot/hi. Then you can see the following in the browser:Hi you !!!

3. Attribute Configuration

Add attributes to the appliction. yml file:

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

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

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

You can also inject attributes into the bean through the ConfigurationProperties annotation, and annotate the bean to the spring container through the Component annotation:

@ConfigurationProperties(prefix="girl")
@Component
publicclassGirlProperties {
 
    private String name;
    privateint age;
 
    public String getName() {
        return name;
    }
 
    publicvoidsetName(String name) {
        this.name = name;
    }
 
    publicintgetAge() {
        return age;
    }
 
    publicvoidsetAge(int age) {
        this.age = age;
    }
}

In addition, you can use the configuration file to create configuration documents for different environments. For details, see the source code:

spring:
  profiles:
    active: prod
4. database operations through jpa

Import jar and add dependency 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 the 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: 123
 
  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true

These are common database configurations. ddl_auto: create indicates creating a table in the database, update indicates updating, and create is required for the first startup, if you want to create a database table using the hibernate annotation, you need to change it to update later.

Create an object girl, which is based on hibernate:

@Entity
publicclassGirl {
 
    @Id
    @GeneratedValue
    private Integer id;
    private String cupSize;
    private Integer age;
 
    publicGirl() {
    }
 
    public Integer getId() {
        return id;
    }
 
    publicvoidsetId(Integer id) {
        this.id = id;
    }
 
    public Integer getAge() {
        return age;
    }
 
    publicvoidsetAge(Integer age) {
        this.age = age;
    }
 
    public String getCupSize() {
        return cupSize;
    }
 
    publicvoidsetCupSize(String cupSize) {
        this.cupSize = cupSize;
    }
}

Create Dao interface. springboot automatically annotates the interface class to the spring container. If you do not need to configure it, you only need to inherit JpaRepository:

// The second parameter indicates the Id type.
publicinterfaceGirlRepextendsJpaRepository<Girl,Integer>{
   }

Create a GirlController, write an api for getting all the girls, and add the girl's api. Just run it:

 
@RestController
publicclassGirlController {
 
    @Autowired
    private GirlRep girlRep;
 
    /**
* Query the list of all girls
     * @return
     */
    @RequestMapping(value = "/girls",method = RequestMethod.GET)
    public List<Girl> getGirlList(){
        return girlRep.findAll();
    }
 
    /**
* Add a girl
     * @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);
    }
 
   } 


 

Related Article

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.