spring/spring-boot常用注解
1.@SpringBootApplication
我们可以把@SpringBootApplication看作是@Configuration、@EnableAutoConfiguration、@ComponentScan注解的集合。
- @EnableAutoConfiguration:启用SpringBoot的自动配置机制
- @ComponentScan: 扫描被@Component(@Service、@Controller)注解的bean,注解会默认扫描该类所在包下的所有的类
- @Configuration: 允许在Spring上下文中注册额外的bean或导入其他配置类。
2.Spring Bean相关
2.1 @Autowired
自动导入对象到类中,被注入进的类同样要被Spring容器管理。例如:service 注入到controller中
@Service
public class UserService {
......
}
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
......
}
2.2@Componet、@repository、@service、@Controller
我们一般使用@Autowire的注解让Spring容器帮我们自动装配bean。
- @Component:通用的注解,可标注任意类为Spring组件。在不知道一个列属于哪一个层的时候可以使用@Component注解。
- @Repository:对应持久层即Dao层,主要用于数据库相关操作。
- @Service:对应服务层,主要涉及一些复杂的逻辑,需要用到Dao。
- @Controller:对应Spring MVC 控制层,主要用于接收用户请求并调用service层返回数据给前端页面。
2.3 @RestController
@RestController注解是@Controller和@ResponseBody的合集,表示这是个控制器bean。并且是将函数的返回值直接填入HTTP响应体中,是REST风格的控制器。
(现在基本都是前后端分离,所以很少用@Controller注解)
单独的使用@Controller不加@ResponseBody的话一般都使用在要返回一个视图的情况下,属于传统的Spring MVC 的应用。对应于前后端不分离的情况。 而@Controller + @ ResponseBody 返回JSON或XML类型数据。
@RestController和@Controller详解.
(引用Guide哥的文章!!!!)
2.4 @Scope
声明Spring Bean 的作用域,使用的方法如下
@Bean
@Scope("singleton")
public Person personSingleton() {
return new Person();
}
四种常见的Spring Bean的作用域:
- singleton:唯一bean实例,Spring中的bean默认都是单例的。
- prototype: 每次请求都会创建一个新的bean实例。
- request:每一次HTTP请求都会产生一个新的bean,该bean仅在当前HTTP request 内有效
- session:每一次HTTP请求都会产生一个新的bean,该bean仅在当前的HTTP session内有效。
2.5@Configuration
一般用来声明配置类,也可以使用@Component注解代替。
@Configuration
public class AppConfig {
@Bean
public TransferService transferService() {
return new TransferServiceImpl(