Spring框架常见注解
1. Spring常见注解
注解 | 说明 |
---|---|
@Component 、@Controller、@Service、@Repository | 使用在类上,用于声明Bean的。 @Component注解相当于spring核心配置文件中的bean标签,@Controller(控制层)、@Service(业务层)、@Repository(数据访问才)都是@Component衍生注解,也是声明bean的。 |
@Autowried、@Resource | 使用在字段上,用于依赖注入的。 @Autowried默认按照类型依赖注入,如果使用的时候存在多个相同类型的bean会报错(唯一bean异常),解决方案:使用@Qualifier与@Autowired组合使用根据指定的bean名称进行依赖注入。 @Resource,他不是spring提供的,默认按照字段名查找(匹配同名的bean),若找到直接装配,若按字段名找不到资源就会按照类型进行查找并装配; |
@Scope | bean的作用范围,例如 单例Singleton(默认)、多例prototype。 |
@Configuration | 指定当前类是一个spring配置类,当创建容器时会从该类上加载注解。 |
@ComponentScan | 用于指定Spring在初始化容器时要扫描的包 |
@Bean | 使用在方法上,会把当前方法的返回值放到Spring容器中。(一般与@Configuration注解组合使用,定义第三方bean) |
@Import | 使用@Import导入的类会被Spring加载到IOC容器中 |
@Aspect、@Before、@After、@Around、@Pointcut | 用于切面编程(AOP) @Aspect(定义切面)、@Before(前置通知)、@After(后置通知)、@Around(环绕通知)、@Pointcut(定义切入点表达式) |
2. SpringMVC常见注解
注解 | 说明 |
---|---|
@RequestMapping | 用于映射请求路径,可以定义在类上和方法上。用在类上表示父路径。@RequestMapping衍生注解有:@GetMapping、@PostMapping、PutMapping、@DeletetMapping |
@RequestBody | 注解实现接收http请求的json数据,将并json转换为Java对象入参。 |
@RequestParam | 指定请求参数的名称 |
@PathVariable | 从请求路径中获取参数,例如 /user/{id},然后通过@PathVariable注解传递给方法的形参 |
@ResponseBody | 将处理请求方法的返回值转化为json对象响应给客户端 |
@RequestHeader | 获取指定的请求头数据 |
@RestController | 用于创建只返回数据而不返回页面的控制器类,@RestController=@Controller +@ResponseBody。 |
3. SpringBoot常见注解
注解 | 说明 |
---|---|
@SpringBootConfiguration | 声明当前类是springboot配置类,是@Configuration衍生注解。 |
@EnableAutoConfiguration | 开启自动配置功能,也可以关闭某个自动配置的选项。 |
@ComponentScan | spring组件扫描 |
@Conditional | 根据特定条件决定是否创建 Bean 或执行特定的配置 |
@SpringBootApplication: | 用于标识主类,表示这是一个类是SpringBoot应用程序的入口。 |