Interview AiBox logo

Interview AiBox 实时 AI 助手,让你自信应答每一场面试

download免费下载
进阶local_fire_department18 次面试更新于 2025-08-23account_tree思维导图

请介绍SpringBoot中常用的注解及其作用

lightbulb

题型摘要

SpringBoot提供了大量注解来简化开发,包括核心注解(@SpringBootApplication)、依赖注入注解(@Autowired, @Resource)、MVC注解(@RestController, @RequestMapping)、数据访问注解(@Entity, @Repository)、AOP注解(@Aspect, @Before)、测试注解(@SpringBootTest, @Test)和配置注解(@Configuration, @Bean)等。这些注解涵盖了从依赖注入、Web开发、数据访问到AOP、测试等各个方面,极大地提高了开发效率。

SpringBoot中常用的注解及其作用

SpringBoot框架提供了大量注解,简化了Java应用的开发过程。下面按照不同类别介绍SpringBoot中常用的注解及其作用。

1. 核心注解

@SpringBootApplication

这是SpringBoot的核心注解,是一个复合注解,包含了以下三个注解的功能:

  • @Configuration: 标识该类为配置类
  • @EnableAutoConfiguration: 启用自动配置机制
  • @ComponentScan: 自动扫描组件
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@EnableAutoConfiguration

启用SpringBoot的自动配置机制,根据类路径下的依赖自动配置Spring应用上下文。

2. 依赖注入注解

@Autowired

自动注入依赖,默认按照类型(byType)进行装配。

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
}

@Resource

按照名称(byName)进行依赖注入,是JSR-250标准的一部分。

@Service
public class UserService {
    @Resource(name = "userRepository")
    private UserRepository userRepository;
}

@Qualifier

当存在多个相同类型的Bean时,配合@Autowired使用,指定注入的Bean名称。

@Service
public class UserService {
    @Autowired
    @Qualifier("userRepositoryImpl")
    private UserRepository userRepository;
}

@Value

注入配置文件中的属性值。

@Value("${app.name}")
private String appName;

3. MVC相关注解

@RestController

组合注解,相当于@Controller + @ResponseBody,表示该类所有方法都返回JSON数据。

@RestController
@RequestMapping("/api/users")
public class UserController {
    // ...
}

@Controller

标识该类为Spring MVC的控制器处理器。

@RequestMapping

用于映射Web请求,可以用在类和方法上。

@RestController
@RequestMapping("/api/users")
public class UserController {
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        // ...
    }
}

@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping

分别对应HTTP的GET、POST、PUT、DELETE、PATCH请求方法的快捷方式。

@PathVariable

从URL路径中获取变量。

@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
    // ...
}

@RequestParam

从请求参数中获取值。

@GetMapping("/search")
public List<User> searchUsers(@RequestParam String name) {
    // ...
}

@RequestBody

将请求体中的JSON数据映射到方法参数上。

@PostMapping
public User createUser(@RequestBody User user) {
    // ...
}

@ResponseBody

将方法返回值直接作为HTTP响应体返回,通常用于返回JSON数据。

4. 数据访问相关注解

@Entity

标识类为JPA实体类,映射到数据库表。

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    private String name;
    // getters and setters
}

@Table

指定实体类映射的数据库表名。

@Entity
@Table(name = "users")
public class User {
    // ...
}

@Id

标识实体类的主键字段。

@GeneratedValue

指定主键生成策略。

@Column

指定字段映射到数据库列的属性。

@Column(name = "user_name", nullable = false, length = 50)
private String name;

@Repository

标识类为数据访问层组件(DAO),同时也会将该类作为异常转换的切入点。

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    // ...
}

@Transactional

声明事务,可以指定事务的传播行为、隔离级别等属性。

@Service
public class UserService {
    @Transactional
    public void createUser(User user) {
        // ...
    }
}

5. AOP相关注解

@Aspect

标识类为切面。

@Aspect
@Component
public class LogAspect {
    // ...
}

@Before

前置通知,在目标方法执行前执行。

@Before("execution(* com.example.service.*.*(..))")
public void beforeMethod(JoinPoint joinPoint) {
    // ...
}

@After

后置通知,在目标方法执行后执行(无论是否抛出异常)。

@AfterReturning

返回通知,在目标方法正常返回后执行。

@AfterThrowing

异常通知,在目标方法抛出异常后执行。

@Around

环绕通知,可以在目标方法执行前后执行自定义逻辑。

@Around("execution(* com.example.service.*.*(..))")
public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
    // 前置逻辑
    Object result = joinPoint.proceed();
    // 后置逻辑
    return result;
}

@Pointcut

定义切入点表达式。

@Pointcut("execution(* com.example.service.*.*(..))")
public void servicePointcut() {}

6. 测试相关注解

@SpringBootTest

用于SpringBoot应用的集成测试,加载完整的Spring应用上下文。

@SpringBootTest
public class UserServiceTest {
    @Autowired
    private UserService userService;
    
    @Test
    public void testCreateUser() {
        // ...
    }
}

@Test

标识方法为测试方法,来自JUnit。

@RunWith

指定测试运行器,如SpringRunner。

@RunWith(SpringRunner.class)
public class UserServiceTest {
    // ...
}

@WebMvcTest

用于Spring MVC控制器的测试,只加载Web层相关的组件。

@WebMvcTest(UserController.class)
public class UserControllerTest {
    @Autowired
    private MockMvc mockMvc;
    
    @Test
    public void testGetUser() throws Exception {
        mockMvc.perform(get("/api/users/1"))
               .andExpect(status().isOk());
    }
}

@DataJpaTest

用于JPA数据访问层的测试,只加载JPA相关的组件。

@MockBean

在测试中创建Mock对象并注入到Spring上下文中。

@SpringBootTest
public class UserServiceTest {
    @MockBean
    private UserRepository userRepository;
    
    @Test
    public void testGetUser() {
        when(userRepository.findById(1L)).thenReturn(Optional.of(new User()));
        // ...
    }
}

7. 配置相关注解

@Configuration

标识类为配置类,Spring容器会将其作为Bean定义的来源。

@Configuration
public class AppConfig {
    @Bean
    public UserService userService() {
        return new UserService();
    }
}

@Bean

声明一个方法,其返回值作为一个Bean注册到Spring容器中。

@ComponentScan

自动扫描组件,默认扫描当前包及其子包下的所有带有@Component、@Service、@Repository、@Controller等注解的类。

@PropertySource

指定属性文件的位置。

@Configuration
@PropertySource("classpath:app.properties")
public class AppConfig {
    // ...
}

@ConfigurationProperties

将配置文件中的属性批量绑定到一个Java对象上。

@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
    private String name;
    private int port;
    // getters and setters
}

@Profile

指定Bean在哪个Profile下生效。

@Configuration
@Profile("dev")
public class DevConfig {
    // ...
}

@Conditional

条件化地注册Bean,满足特定条件时才创建Bean。

@Bean
@ConditionalOnClass(DataSource.class)
public DataSource dataSource() {
    // ...
}

8. 其他常用注解

@Component

通用的组件注解,标识一个类为Spring管理的组件。

@Service

标识类为业务逻辑层组件。

@Service
public class UserService {
    // ...
}

@Controller

标识类为Web层控制器组件。

@Repository

标识类为数据访问层组件。

@Primary

当存在多个相同类型的Bean时,指定优先注入的Bean。

@Primary
@Bean
public DataSource primaryDataSource() {
    // ...
}

@Lazy

延迟初始化Bean,第一次使用时才创建。

@Lazy
@Service
public class UserService {
    // ...
}

@Scope

指定Bean的作用域,如singleton、prototype等。

@Bean
@Scope("prototype")
public User user() {
    return new User();
}

@PostConstruct

在Bean初始化完成后执行的方法。

@Component
public class UserService {
    @PostConstruct
    public void init() {
        // 初始化逻辑
    }
}

@PreDestroy

在Bean销毁前执行的方法。

@Component
public class UserService {
    @PreDestroy
    public void cleanup() {
        // 清理逻辑
    }
}

SpringBoot注解关系图

--- title: SpringBoot注解关系图 --- classDiagram class SpringBootApplication { <<annotation>> } class Configuration { <<annotation>> } class EnableAutoConfiguration { <<annotation>> } class ComponentScan { <<annotation>> } class Component { <<annotation>> } class Service { <<annotation>> } class Repository { <<annotation>> } class Controller { <<annotation>> } class RestController { <<annotation>> } class Autowired { <<annotation>> } class Value { <<annotation>> } class Bean { <<annotation>> } SpringBootApplication --> Configuration SpringBootApplication --> EnableAutoConfiguration SpringBootApplication --> ComponentScan Service --|> Component Repository --|> Component Controller --|> Component RestController --|> Controller

SpringBoot请求处理流程

--- title: SpringBoot请求处理流程 --- sequenceDiagram participant Client participant DispatcherServlet participant Controller participant Service participant Repository participant Database Client->>DispatcherServlet: HTTP请求 DispatcherServlet->>Controller: 路由到对应Controller Controller->>Service: 调用业务逻辑 Service->>Repository: 调用数据访问 Repository->>Database: 执行SQL查询 Database-->>Repository: 返回数据 Repository-->>Service: 返回实体对象 Service-->>Controller: 返回处理结果 Controller-->>DispatcherServlet: 返回响应数据 DispatcherServlet-->>Client: HTTP响应

总结

SpringBoot通过提供丰富的注解,极大地简化了Java应用的开发。这些注解涵盖了从依赖注入、Web开发、数据访问到AOP、测试等各个方面。掌握这些注解的使用和作用,是开发高质量SpringBoot应用的基础。

account_tree

思维导图

Interview AiBox logo

Interview AiBox — 面试搭档

不只是准备,更是实时陪练

Interview AiBox 在面试过程中提供实时屏幕提示、AI 模拟面试和智能复盘,让你每一次回答都更有信心。

AI 助读

一键发送到常用 AI

SpringBoot提供了大量注解来简化开发,包括核心注解(@SpringBootApplication)、依赖注入注解(@Autowired, @Resource)、MVC注解(@RestController, @RequestMapping)、数据访问注解(@Entity, @Repository)、AOP注解(@Aspect, @Before)、测试注解(@SpringBootTest, @Test)和配置注解(@Configuration, @Bean)等。这些注解涵盖了从依赖注入、Web开发、数据访问到AOP、测试等各个方面,极大地提高了开发效率。

智能总结

深度解读

考点定位

思路启发

auto_awesome

相关题目

请介绍C++11中引入的主要新特性

C++11引入了众多现代化特性,包括:1)自动类型推导(auto)简化了复杂类型声明;2)基于范围的for循环提高了遍历容器的便利性;3)智能指针(unique_ptr, shared_ptr, weak_ptr)提供了更安全的内存管理;4)Lambda表达式支持匿名函数定义;5)右值引用和移动语义优化了资源转移性能;6)nullptr作为明确的空指针表示;7)强类型枚举(enum class)避免命名空间污染;8)constexpr支持编译时计算;9)统一初始化语法({})适用于各种类型;10)using关键字提供更清晰的类型别名定义;11)可变参数模板增强了模板灵活性;12)线程支持库实现标准多线程编程;13)新容器(array, forward_list, unordered容器)和算法丰富了标准库功能。这些特性使C++更现代化、安全且易用。

arrow_forward

设计一个社交朋友圈系统,支持用户发布动态、好友查看动态等功能,请设计其数据结构和系统架构

朋友圈系统设计涉及数据结构和系统架构两个方面。数据结构包括用户表、好友关系表、动态表、媒体表、点赞表和评论表等。系统架构采用分层设计,包括客户端层、接入层、业务逻辑层、数据存储层和基础设施层。核心功能包括发布动态、获取好友动态、点赞评论等。性能优化方面考虑了缓存策略、数据库优化和服务优化。系统设计还考虑了功能扩展和技术扩展,以适应未来的发展需求。

arrow_forward

请列举并解释进程间通信的方式。

进程间通信(IPC)是操作系统提供的重要机制,主要方式包括:管道(匿名/命名)、消息队列、共享内存、信号量、信号、套接字和文件映射。管道适用于父子进程通信;消息队列支持异步通信;共享内存是最快的IPC方式;信号量用于进程同步;信号适合异步通知;套接字最通用,可用于网络通信;文件映射支持数据持久化。不同方式各有优缺点,应根据具体场景选择。

arrow_forward

请列举一些Linux常用命令及其用途

Linux常用命令按功能可分为八大类:文件和目录操作(ls, cd, cp, mv, rm)、文本处理(cat, grep, sed, awk)、系统信息管理(uname, top, df, free)、网络相关(ping, ssh, curl, netstat)、权限管理(chmod, chown, sudo)、进程管理(ps, kill, jobs)、搜索查找(find, locate, which)和压缩解压(tar, zip, gzip)。掌握这些命令是后端开发的基础技能,能够有效进行系统管理、文件处理、问题排查和日常开发工作。

arrow_forward

请解释C++中虚函数的实现原理

C++中虚函数的实现原理主要依赖于虚函数表(vtable)和虚指针(vptr)。每个包含虚函数的类都有一个虚函数表,存储该类虚函数的地址;每个对象实例包含一个虚指针,指向其类的虚函数表。当通过基类指针或引用调用虚函数时,系统会通过虚指针找到虚函数表,再从表中获取实际要调用的函数地址,从而实现运行时多态。这种机制虽然有一定的性能开销,但为C++提供了强大的面向对象多态能力。

arrow_forward