1.SpringBoot入门

SpringBoot从零开始部署一个项目,并让它运行起来,网上已经有很多这样的例子,所以在这里就不再赘述了。

笔者也是一个SpringBoot的初学者,所以此博客用来充当学习的笔记和总结学习过程中遇到的一些问题以及解决方法。

1.@SpringBootApplication

@SpringBootApplication注解等价于@Configuration, @EnableAutoConfiguration and @ComponentScan

运行SpringBoot项目时,如果启动类之前没有加上这个注解可能会报错,此注解表明此项目是一个SpringBoot项目。

用了此注解之后,启动之后,系统会自动的扫描和启动类在同一包内,或者子包类的组建,纳入Spring容器之内管理,而不在子包内或者同一包内的,Spring就无法扫描到。

也可以自己指定,扫描的路径:

@SpringBootApplication(scanBasePackages = "包路径")

或者加上

@ComponentScan(basePackages = {"包路径1", "包路径2"})

同时也可以使用exclude和excludeName排除不需要扫描和纳入容器管理的类

@SpringBootApplication(excludeName = {"com.zhihao.miao.springboot.People"})

2.pom.xml中依赖配置完成之后,运行SpringBoot出现错误,报ClassNotFound。

  <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.4.1.RELEASE</version>
  <relativePath/>
   </parent>

解决方法在于,上述的继承的org.springframework,boot的版本太高,只需要把version版本降低就可以成功运行。

本来是2.0.0运行报错,找不到相关类,变成1.4.1之后就可以成功运行了。

3.SpringBoot中常用的一些注解

@SpringBootApplication:
包含@Configuration、@EnableAutoConfiguration、@ComponentScan
通常用在主类上。

@Repository:
用于标注数据访问组件,即DAO组件。

@Service:
用于标注业务层组件。 

@RestController:
用于标注控制层组件(如struts中的action),包含@Controller和@ResponseBody。

@ResponseBody:
表示该方法的返回结果直接写入HTTP response body中
一般在异步获取数据时使用,在使用@RequestMapping后,返回值通常解析为跳转路径,加上@responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如异步获取json数据,加上@responsebody后,会直接返回json数据。

@Component:
泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。

@ComponentScan:
组件扫描。个人理解相当于<context:component-scan>,如果扫描到有@Component @Controller @Service等这些注解的类,则把这些类注册为bean。

@Configuration:
指出该类是 Bean 配置的信息源,相当于XML中的<beans></beans>,一般加在主类上。

@Bean:
相当于XML中的<bean></bean>,放在方法的上面,而不是类,意思是产生一个bean,并交给spring管理。

@EnableAutoConfiguration:
让 Spring Boot 根据应用所声明的依赖来对 Spring 框架进行自动配置,一般加在主类上。

@AutoWired:
byType方式。把配置好的Bean拿来用,完成属性、方法的组装,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。
当加上(required=false)时,就算找不到bean也不报错。

@Qualifier:
当有多个同一类型的Bean时,可以用@Qualifier("name")来指定。与@Autowired配合使用

@Resource(name="name",type="type"):
没有括号内内容的话,默认byName。与@Autowired干类似的事。

 

@RequestMapping:

RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
该注解有六个属性:
params:指定request中必须包含某些参数值是,才让该方法处理。
headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。
value:指定请求的实际地址,指定的地址可以是URI Template 模式
method:指定请求的method类型, GET、POST、PUT、DELETE等
consumes:指定处理请求的提交内容类型(Content-Type),如application/json,text/html;
produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回

@RequestParam:
用在方法的参数前面。
@RequestParam String a =request.getParameter("a")。

@PathVariable:

路径变量。参数与大括号里的名字一样要相同。

RequestMapping("user/get/mac/{macAddress}")
public String getByMacAddress(@PathVariable String macAddress){
  //do something;
}
 

@Profiles
Spring Profiles提供了一种隔离应用程序配置的方式,并让这些配置只能在特定的环境下生效。
任何@Component或@Configuration都能被@Profile标记,从而限制加载它的时机。

@Configuration
@Profile("prod")
public class ProductionConfiguration {
    // ...
}
 

@ConfigurationProperties
Spring Boot将尝试校验外部的配置,默认使用JSR-303(如果在classpath路径中)。
你可以轻松的为你的@ConfigurationProperties类添加JSR-303 javax.validation约束注解:

复制代码
@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {
@NotNull
private InetAddress remoteAddress;
// ... getters and setters
}
复制代码
 

全局异常处理

@ControllerAdvice:
包含@Component。可以被扫描到。
统一处理异常。

@ExceptionHandler(Exception.class):
用在方法上面表示遇到这个异常就执行以下方法。

还有几个特殊的注解

@PathVaribale 获取url中的数据

@RequestParam 获取请求参数的值

@GetMapping 组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写

@PathVaribale 获取url中的数据
看一个例子,如果我们需要获取Url=localhost:8080/hello/id中的id值,实现代码如下:

@RestController
public class HelloController {

    @RequestMapping(value="/hello/{id}",method= RequestMethod.GET)
    public String sayHello(@PathVariable("id") Integer id){
        return "id:"+id;
    }
}


同样,如果我们需要在url有多个参数需要获取,则如下代码所示来做就可以了。

@RestController
public class HelloController {

    @RequestMapping(value="/hello/{id}/{name}",method= RequestMethod.GET)
    public String sayHello(@PathVariable("id") Integer id,@PathVariable("name") String name){
        return "id:"+id+" name:"+name;
    }
}

以上,通过@PathVariable注解来获取URL中的参数时的前提条件是我们知道url的格式时怎么样的。

只有知道url的格式,我们才能在指定的方法上通过相同的格式获取相应位置的参数值。

一般情况下,url的格式为:localhost:8080/hello?id=98,这种情况下该如何来获取其id值呢,这就需要借助于@RequestParam来完成了

@RequestParam 获取请求参数的值
直接看一个例子,如下

@RestController
public class HelloController {

    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(@RequestParam("id") Integer id){
        return "id:"+id;
    }
}

在浏览器中输入地址:localhost:8080/hello?id=1000,可以看到如下的结果: 


当我们在浏览器中输入地址:localhost:8080/hello?id ,即不输入id的具体值,此时返回的结果为null。具体测试结果如下:

但是,当我们在浏览器中输入地址:localhost:8080/hello ,即不输入id参数,则会报如下错误:

@RequestParam注解给我们提供了这种解决方案,即允许用户不输入id时,使用默认值,具体代码如下:

@RestController
public class HelloController {
    @RequestMapping(value="/hello",method= RequestMethod.GET)
    //required=false 表示url中可以不穿入id参数,此时就使用默认参数
    public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){
        return "id:"+id;
    }
}
测试结果如下; 


如果在url中有多个参数,即类似于localhost:8080/hello?id=98&&name=wojiushimogui这样的url,同样可以这样来处理。具体代码如下:

/**
 * Created by wuranghao on 2017/4/7.
 */
@RestController
public class HelloController {

    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(@RequestParam("id") Integer id,@RequestParam("name") String name){
        return "id:"+id+ " name:"+name;
    }
}

猜你喜欢

转载自blog.csdn.net/star_kite/article/details/84950220