Springboot系列文章4:常用注解

Springboot系列文章

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。




前言

Springboot项目中使用注解替代xml配置,那么常用注解有哪些,都有什么作用。


一、配置相关

1.@Configuration

proxyBeanMethods:代理bean的方法
1)Full(proxyBeanMethods = true)、【保证每个@Bean方法被调用多少次返回的组件都是单实例的】
2) Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】
3)组件依赖必须使用Full模式默认。其他默认是否Lite模式

@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件

2.@Bean

配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的

3. @Conditional相关注解

从用于条件加载bean。如互相依赖情况下,假设B依赖A,这时可以判断B是否存在,如果B存在,则加载A。

@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
//@ConditionalOnBean(name = "tom")
@ConditionalOnMissingBean(name = "tom")
public class MyConfig {
}

在这里插入图片描述

4. @Import({User.class, DBHelper.class})

给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名又
给容器导入组件,调用无参构造器,自动创建出组件对象;默认名字=全类名

@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
public class MyConfig {

}

5. @ImportResource

导入原生配置xml配置文件,用于适应老系统。

a. 创建一个xml配置文件

======================beans.xml=========================
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="haha" class="com.springboot2.bean.User">
        <property name="name" value="zhangsan"></property>
        <property name="age" value="18"></property>
    </bean>

    <bean id="hehe" class="com.springboot2.bean.Pet">
        <property name="name" value="tomcat"></property>
    </bean>
</beans>

b. 配置类前引入bean

@ImportResource(“classpath:beans.xml”)
public class MyConfig {

}

6.配置绑定

读取配置类中的设置的值,一般用于参数初始化;目前实现方法,将配置参数读取到java bean中。
配置文件application.properties的参数

mycar.brand=BYD
mycar.price=100000

bean的Car类

package com.springboot2.bean;

import org.apache.logging.log4j.util.Strings;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

public class Car {
    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }
    private String brand;
    private Integer price;
    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
}

a. @Component +@ConfigurationProperties

在bean类前增加以下两个属性,.如Car.java文件中
@Component
@ConfigurationProperties(prefix = “mycar”).

b. @EnableConfigurationProperties+@ConfigurationProperties

在配置类前增加:@EnableConfigurationProperties(Car.class)
在bean类前增加:@ConfigurationProperties(prefix = “mycar”).

注意事项:beans.xml中要实例化的类,必须有默认构造函数(即不带参数的构造函数)

7. @Component

8. @SpringBootApplication

等同于一下三个注解
@SpringBootConfiguration : 代表当前是一个配置类
@ComponentScan(“com.atguigu.boot”):指定扫描哪些,Spring注解;
@EnableAutoConfiguration :

@AutoConfigurationPackage   自动配置包?指定了默认的包规则
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {}

a. @AutoConfigurationPackage

自动配置包?指定了默认的包规则

@Import(AutoConfigurationPackages.Registrar.class)  //给容器中导入一个组件
public @interface AutoConfigurationPackage {}

//利用Registrar给容器中导入一系列组件
//将指定的一个包下的所有组件导入进来?MainApplication 所在包下。

b. @Import(AutoConfigurationImportSelector.class)

1、利用getAutoConfigurationEntry(annotationMetadata);给容器中批量导入一些组件
2、调用List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes)获取到所有需要导入到容器中的配置类
3、利用工厂加载 Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader);得到所有的组件
4、从META-INF/spring.factories位置来加载一个文件。
	默认扫描我们当前系统里面所有META-INF/spring.factories位置的文件
    spring-boot-autoconfigure-2.3.4.RELEASE.jar包里面也有META-INF/spring.factories    

9.SpringBoot最佳实践

总结:
● SpringBoot先加载所有的自动配置类 xxxxxAutoConfiguration
● 每个自动配置类按照条件进行生效,默认都会绑定配置文件指定的值。xxxxProperties里面拿。xxxProperties和配置文件进行了绑定
● 生效的配置类就会给容器中装配很多组件
● 只要容器中有这些组件,相当于这些功能就有了
● 定制化配置
○ 用户直接自己@Bean替换底层的组件
○ 用户去看这个组件是获取的配置文件什么值就去修改。
xxxxxAutoConfiguration —> 组件 —> xxxxProperties里面拿值 ----> application.properties

二、控制相关

1. @Controller

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

//index页面内容就是 “源源”
在这里插入图片描述

2.@RestController

解释意思是:@RestController注解相当于@ResponseBody+ @Controller合在一起的作用。

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

在这里插入图片描述

3.@ResponseBody

类对象的json返回

4.@ControllerAdvise

在Spring里,我们可以使用@ControllerAdvice来声明一些全局性的东西,最常见的是结合@ExceptionHandler注解用于全局异常的处理。@ControllerAdvice是在类上声明的注解,其用法主要有三点:
@ExceptionHandler注解标注的方法:用于捕获Controller中抛出的不同类型的异常,从而达到异常全局处理的目的;
@InitBinder注解标注的方法:用于请求中注册自定义参数的解析,从而达到自定义请求参数格式的目的;
@ModelAttribute注解标注的方法:表示此方法会在执行目标Controller方法之前执行 。

package com.springboot2.helloworld;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class HelloworldException {

    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map errorHandler(Exception ex) {
        Map map = new HashMap();
        map.put("code", 400);
        map.put("msg", ex.getMessage());
        System.out.println("fum:"+ex.getMessage());
        return map;
    }

}

三 业务相关

1. @Service

业务组件

四 数据相关

1.@Repository

数据库组件

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值