Spring boot 常用注解

一、组件添加

@SpringBootApplication

声明这是一个SpringBoot应用,表明该类是主程序类。
参数:scanBasePackages:指定扫描包的范围。
由以下三个注解组成
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(“com.silence”)

@Controller

声明这是一个控制层类,用来与web交互。

@ResponseBody

声明返回的数据类型是json,可写在方法上,也可以写在类上。

@RestController

写在类上,是@Controller和@ResponseBody的组合。

@RequestMapping(“/hello”)

映射的地址,可以写在方法上,也可以写在类上。

@Service

业务层,写业务逻辑代码,写在接口或类上。

@Repository

数据库组件

@Component

代表一个组件

@Configuration

1.声明一个配置类,默认单实例。
2.配置类本身也是一个组件。
3.proxyBeanMethods:代理bean的方法
Full(proxyBeanMethods=true) //轻量级模式
Lite(proxyBeanMethods=false) //全模式
用来解决组件依赖的问题。
配置类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断。
配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式。

使用@Bean给容器中添加组件,用方法名作为组件的id,返回值类型就是组件的类型,返回的值就是组件在容器中的实例。@Bean(“user1”)可以指定组件名称。

@Import

写在组件类上。
将指定类型的组件导进去,在容器中自动的创建出指定类型的组件。默认组件的名字就是全类名。

@Conditional

条件装配:满足Conditional指定的条件,则进行组件注入
Conditional

二、原生配置文件引入

@ImportResource

原生配置文件引入,写在类上。

@ImportResource("classpath:beans.xml")
public class MyConfig {}

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.silence.bean.User">
        <property name="name" value="zhangsan"></property>
        <property name="age" value="18"></property>
    </bean>

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

三、配置绑定

@ConfigurationProperties

该注解说明和 springboot 核心配置文件进行属性绑定

// car 实体类
@ConfigurationProperties(prefix="Car")
public class Car {}

@EnableConfigurationProperties + @ConfigurationProperties

在配置类中使用该组注解。
实体类上不用标:@Component
只需要:@ConfigurationProperties

@EnableConfigurationProperties(Car.class)
//1、开启Car配置绑定功能
//2、把这个Car这个组件自动注册到容器中
public class MyConfig {
}

// car 实体类
@ConfigurationProperties(prefix="Car")
public class Car {}

//application.perperties
Car.xxx = xxx

@Component + @ConfigurationProperties

在实体类型上注册组件,然后在配置文件中指定参数值

@Component
@ConfigurationProperties(prefix="Car")
public class Car {}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值