Spring Boot 注解—常用注解

注:该部分内容包含一些常用注解,如果没有学习过java注解的同学可以先看一下上一小节的内容Spring Boot 注解—基本知识 ,不看也没关系,下面就开始本节内容。

@Configuration注解

@Configuration注解意思是往容器中加入一个组件,该组件的主要作用是进行一些配置,相当于之前配置的配置文件,下面我们用两种方式对其进行演示:
准备工作
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.itbofeng</groupId>
    <artifactId>SpringDemo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

配置文件方式
1、创建类路径配置文件beans.xml
2、创建User类

package com.itbofeng.bean;
/**
 * 描述:User Bean 用来测试
 */
public class User {
    private String name;
    private Integer age;
    public User() {
    }
    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
    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;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

2、在配置文件中加入User bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="user" class="com.itbofeng.bean.User">
        <property name="name" value="zhangsan"></property>
        <property name="age" value="13"></property>
    </bean>
</beans>

3、运行测试

import com.itbofeng.bean.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 描述:测试类
 */
public class MainConfigTest {
    @Test
    public void testXml(){
        //通过配置文件创建容器,需要传入配置文件
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("beans.xml");
        //获取bean
        User user= (User) applicationContext.getBean("user");
        System.out.println(user);
    }
}

运行结果

注解方式
1、创建配置类MainConfig.java
2、注册组件用@Bean注解
我们看一下代码

package com.itbofeng;

import com.itbofeng.bean.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 描述:该类对@Configuration注解进行讲解
 */
@Configuration
public class MainConfig {
    /**
     * 给容器中加入Bean,相当于配置文件总的bena标签
     * id 默认是方法名称,也可以指定id
     * class 即返回值类型
     */
    @Bean
    public User user(){
        return new User("lisi",18);
    }
}

以上配置类就等同于beans.xml中的内容
3、运行测试

    @Test
    public void testAnnoation(){
        //通过注解创建容器,需要传入配置类
        ApplicationContext applicationContext=new AnnotationConfigApplicationContext(MainConfig.class);
        //获取bean
        User user= (User) applicationContext.getBean("user");
        System.out.println(user);
    }
运行结果

有了该例子相信大家对@Configuration有了一个基本的认识,其就相当于Spring配置文件的功能,不过是以注解的方式进行体现,之前我们在配置文件中多采用包扫描的方式进行,那么这种方式在配置类中如何体现呢,下面我们引入第二个注解@ComponentScan包扫描注解

@ComponentScan注解

@ComponentScan注解就相当于 xml配置文件中的context:component-scan标签,下面讲解一下他的基本使用方法:
xml

<context:component-scan base-package="com.itbofeng"></context:component-scan>

java

@Configuration
@ComponentScan("com.itbofeng")
public class MainConfig {
  //...
}

这样就可以对com.itbofeng包下的@Controller、@Service、@Component、@Respoitory、@Component标注的类进行扫描,并由Spring容器进行管理,当然spring并不是这么简单的,它还可以进行排除,仅包含,我们看一下xml和java的语法
xml

    <!--包扫描、如果想要include-filter起作用需要设置use-default-filters="false",禁用默认过滤规则-->
    <context:component-scan base-package="com.itbofeng" use-default-filters="false">
        <!--排除-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
        <!--仅包括-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"></context:include-filter>
    </context:component-scan>

java

@Configuration
@ComponentScan(value = "com.itbofeng",excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class})
},
includeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Service.class})
},useDefaultFilters = false)
public class MainConfig {
  //...
}

对于jdk1.8及以上@ComponentScan支持重复注解,另外还有@ComponentScans注解可以写多个@ComponentScan注解,另外需要说明的两种过滤方式排除和仅包含在一个包扫描中仅可出现一个。
关于@ComponentScan.Filter.type的取值大家可以参考:https://www.cnblogs.com/kevin-yuan/p/5068448.html
我们之前看到过@Bean注解,但并未对该注解进行详细介绍
@Bean
前面我们初步体验了一下@bean注解的作用也很简单常用来标注在方法上面,来表示往spring容器中添加一个组件如上面的利用@Bean往容器中添加一个User组件,在xml中我们不仅能够往容器中添加一个bean而且还能设置lazy-init、scope的属性,这些属性在注解里面可以这样使用

    @Lazy
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    @Bean
    public User user(){
        return new User("lisi",18);
    }

等同于

<bean id="user" class="com.itbofeng.bean.User" scope="singleton" lazy-init="true">
        <property name="name" value="zhangsan"></property>
        <property name="age" value="13"></property>
</bean>

@Component、@Configuration、@Controller、@Service、@Repository
其实在web开发中我们最常用的组件是@Component、@Configuration、@Controller、@Service、@Repository这几个注解都有一个作用,往容器中添加一个组件他们都是@Component组合注解,他们标注在类上面,表示往spring容器中添加一个组件,@Controller用来标注在Controller上面,@Service用来标注Service层上面,@Repository用来标注在持久层上面,@Configuration用来标注在配置类上,@Component用来标注在其他组件上面。
@RequestMapping
在SpringMVC中还有个重要的注解@RequestMapping,它是用来做地址映射的,就是说,我们一个请求,该如何映射到我们的方法上面。它可用于类或方法上,用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。RequestMapping注解有六个属性,其中常用的有value, method、非常用的有params,headers、consumes,produces,value:指定请求的实际地址,method: 指定请求的method类型, GET、POST、PUT、DELETE等(符合Rest风格);params: 指定request中必须包含某些参数值是,才让该方法处理。headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回,例子:

package com.itbofeng.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class UserController {
    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String hello(){
        return "hello";
    }
}

@ResponseBody
如果我们配置了视图解析器ViewResolver,如果我们访问 localhost:8080/hello还并不能够返回hello,其会返回视图解析器的前缀+hello+后缀的页面,如果我们想要其向浏览器返回hello内容,则需要@ResponseBody注解,该注解就是将返回值直接返回给浏览器,如果返回值是一个对象,则会返回该对象的json对象,其可以标注在方法上表示该方法返回遵守该规则,也可以标注在类上,表示该类下的所有方法都遵守该规则。用法如下:

    @ResponseBody
    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String hello(){
        return "hello";
    }

@RestController
@RestController=@Controller+@ResponseBody
@PathVariable、@RequestParam
@PathVariable 路径变量,主要是将路径中的值映射为变量(Rest编程风格推荐),
@RequestParam 请求参数,主要是获取请求中的参数
下面我们举例说明:
地址① http://localhost:8080/hello?name=lisi
地址② http://localhost:8080/hello/lisi
我们通过两种方式来获取变量请求中的lisi,
@RequestParam 方式

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

@PathVariable 方式

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

注意:请求路径的变化
今天注解部分就先将到这里,后面我们在学习过程中学到什么,再具体讲解其用法,关于这些注解的在什么时候起作用的呢,需要我们学习了Spring的运行流程之后,才能进一步的进行深入了解,下一节,我们学习一下往容器中添加Bean的几种方式。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容