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<Student> 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

<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>

    <groupId>com.qytx</groupId>
    <artifactId>girl</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>girl</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration> <!--fork : 如果没有该项配置,肯呢个devtools不会起作用,即应用不会restart -->
                    <fork>true</fork>
                </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.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
</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());
    }
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

发疯的man

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值