springBoot常见问题

参考http://blog.csdn.net/Peng_Hong_fu/article/details/53691705

不用每个接口都加@ResponseBody就可以实现返回json数据

解决方法:

把controller上面的@controller注解换成@RestController这个。

设置全局捕获异常类

场景:当接口发生错误的时候就跑到那个类里面执行对应的方法,而不会出现错误页面,更人性化。
解决方法:
1.写一个controller类,用@ControllerAdvice注解标识
2.类里加上这样一句话@ExceptionHandler(RuntimeException.class)
3.任意写一个方法就可以。

@ControllerAdvice
public class ErroController {


    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Map<String,String> xx(){
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("500","错误");
        return map;
    }
}

设置启动main入口函数的时候扫描指定的controller类

解决方法:

在该main函数的类上面加上@ComponentScan(basePackages = "controller")这样的注解。后面是路径

修改默认的端口号

在resource目录下创建application.properties文件,默认加载,无需其他配置。
写上

server.port=8888

springboot和mybaties集成

application.properties

server.port=9999

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root

dao

package dao;

import domian.Student;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface PayOrderDao {
      @Select("select * from student;")
      public List selectPayOrder();

}

app

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

/**
 * SpringBoot启动类
 * 
 * @author Administrator
 *
 */

@ComponentScan(basePackages = { "controller" ,"service"})
@MapperScan(basePackages={ "dao" })
@EnableAutoConfiguration
public class App {

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

}

springboot的定时任务

附上http://cron.qqe2.com/

package com.itmayiedu.controller;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * 定时任务调度
 * 
 * @author Administrator
 *
 */
@Configuration
@EnableScheduling // 启用定时任务
public class SchedulingConfig {
    int count = 0;

    @Scheduled(cron = "0/1 * * * * ?") // 每20秒执行一次
    public void scheduler() {
        count++;
        System.out.println("定时任务已经出发,这是第" + count + "次");
    }

}

springboot和jpa集成,启动springboot就可以在数据库中创建表。

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8
    username: root
    password: root

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

pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>com.qytxgroupId>
    <artifactId>girlartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <packaging>jarpackaging>

    <name>girlname>
    <description>Demo project for Spring Bootdescription>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>1.5.9.RELEASEversion>
        <relativePath/> 
    parent>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jpaartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration> 
                    <fork>truefork>
                configuration>
            plugin>
        plugins>
    build>


project>

实体类
注意:必须有主键id和无参构造方法

package com.qytx;


import org.springframework.stereotype.Component;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 * Created by lilipo on 2018/1/28.
 */
@Component
@Entity
public class girl {
    @Id
    @GeneratedValue
    private Integer id;
    private  String name;
    private Integer age;

    public girl() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {

        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

jpa的增删改查,超级简单,不用写一条sql语句

dao层是一个接口,需要继承JpaRepository

public interface girlDao extends JpaRepository<girl,Integer> {
}

在controller层引入就可以

查讯全部
findAll()
查询一个通过id
findOne()
保存
save()
更新(前提是设置好idsave()
删除根据id
delete()

自定义自己的查询方法  需要在接口dao层的接口拓展,但是方法名有讲究的,比如说根据age查询
方法名为  findByAge()   才可以

springboot的事物注解

在需要事物的方法上加上
@Transactuional

springboot的————————————————aop

首先引入pom

 <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-aopartifactId>
dependency>

写个切面类
注意表达式的写法

package com.qytx;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * Created by lilipo on 2018/1/28.
 */
@Aspect
@Component
public class HelloAspect {
    @Before("execution(public * Hello.*(..))")
    public void b1(){
        System.out.println("1111111111");
    }
    @After("execution(public * Hello.*(..))")
    public void b2(){
        System.out.println("2222222222");
    }
}

这样写的话每个方法都要写表达式好麻烦,所以把表达式抽出来。看下面
这个和上面作用一样,只不过更加灵活

package com.qytx;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * Created by lilipo on 2018/1/28.
 */
@Aspect
@Component
public class HelloAspect {
    @Pointcut("execution(public * Hello.*(..))")
    public void point(){

    }

    @Before("point()")
    public void b1(){
        System.out.println("1111111111");
    }
    @After("point()")
    public void b2(){
        System.out.println("2222222222");
    }
}

日志的实现

package com.qytx;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.omg.CORBA.Object;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by lilipo on 2018/1/28.
 */
@Aspect
@Component
public class HelloAspect {

    private final  static Logger log= LoggerFactory.getLogger(HelloAspect.class);
    @Pointcut("execution(public * Hello.*(..))")
    public void point(){

    }

    //想得到方法名需要传入JoinPoint这个类
    @Before("point()")
    public void b1(JoinPoint joinPoint){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //url
        log.info("url={}",request.getRequestURL());
        //method类型 get 或者 post
        log.info("methodType={}",request.getMethod());
        //ip
        log.info("ip={}",request.getRemoteAddr());
        //类方法
        log.info("method={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
        //参数
        log.info("args={}",joinPoint.getArgs());
    }
    @After("point()")
    public void b2(){
        log.info("啦啦啦啦啦啦");
    }

    /**
     * 得到返回之后的数据
     * @param object
     */
    @AfterReturning(returning = "object", pointcut = "point()")
    public void doAfterReturing(Object object){
        log.info("response={}",object.toString());
    }
}

你可能感兴趣的:(springboot)