在 Spring 框架中,注解(Annotation)是实现依赖注入(DI)和声明式编程的核心工具。以下是一些常用的 Spring 注解,按功能分类介绍:
1. 组件扫描与声明
@Component
用途:标记一个类为 Spring 的组件,使其被 Spring 容器管理。
示例
@Component
public class MyComponent {
public void doSomething() {
System.out.println("Doing something...");
}
}
@Service
用途:标记一个类为服务层组件,通常用于业务逻辑层。
示例:
@Service
public class MyService {
public void performService() {
System.out.println("Performing service...");
}
}
@Repository
用途:标记一个类为数据访问层组件,通常用于 DAO(数据访问对象)。
示例:
@Repository
public class MyRepository {
public void saveData() {
System.out.println("Saving data...");
}
}
@Controller
用途:标记一个类为控制器层组件,通常用于处理 HTTP 请求。
示例:
@Controller
public class MyController {
@RequestMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
@RestController
用途:标记一个类为 RESTful 控制器,用于处理 RESTful 请求并直接返回数据(而非视图)。
示例:
@RestController
public class MyRestController {
@GetMapping("/api/hello")
public String sayHello() {
return "Hello, World!";
}
}
@Configuration
用途:标记一个类为配置类,用于定义 Spring 的 Bean 或配置。
示例:
@Configuration
public class AppConfig {
@Bean
public MyComponent myComponent() {
return new MyComponent();
}
}
2. 依赖注入
@Autowired
用途:自动注入依赖的 Bean。
示例:
@Service
public class MyService {
@Autowired
private MyRepository myRepository;
public void performService() {
myRepository.saveData();
}
}
@Qualifier
用途:用于指定注入的 Bean 的名称,当存在多个相同类型的 Bean 时使用。
示例:
@Autowired
@Qualifier("myRepository")
private MyRepository repository;
@Resource
用途:与 `@Autowired` 类似,但更符合 Java 标准,支持按名称注入。
示例:
@Resource(name = "myRepository")
private MyRepository repository;
3. Bean 配置
`@Bean`
用途:用于在配置类中声明一个 Bean。
示例:
@Configuration
public class AppConfig {
@Bean
public MyComponent myComponent() {
return new MyComponent();
}
}
`@Scope`
用途:定义 Bean 的作用域(如 `singleton`、`prototype` 等)。
示例:
@Component
@Scope("prototype")
public class MyComponent {
// ...
}
4. 生命周期
`@PostConstruct`
用途:标记一个方法在 Bean 初始化后执行。
示例:
@Component
public class MyComponent {
@PostConstruct
public void init() {
System.out.println("Bean initialized");
}
}
`@PreDestroy`
用途:标记一个方法在 Bean 销毁前执行。
示例:
@Component
public class MyComponent {
@PreDestroy
public void destroy() {
System.out.println("Bean destroyed");
}
}
5. 事务管理
`@Transactional`
用途:声明方法在事务上下文中执行。
示例:
@Service
public class MyService {
@Transactional
public void performService() {
// 数据库操作
}
}
6. AOP(面向切面编程)
`@Aspect`
用途:标记一个类为切面类。
示例:
@Aspect
@Component
public class MyAspect {
@Before("execution(* com.example.MyService.*(..))")
public void beforeAdvice() {
System.out.println("Before method execution");
}
}
`@Before`、`@After`、`@AfterReturning`、`@AfterThrowing`、`@Around`
用途:定义切点的执行时机。
示例:
@AfterReturning(pointcut = "execution(* com.example.MyService.*(..))", returning = "result")
public void afterReturning(Object result) {
System.out.println("Method returned: " + result);
}
7. 测试相关
`@SpringBootTest`
用途:用于 Spring Boot 应用的集成测试。
示例:
@SpringBootTest
public class MyApplicationTests {
@Autowired
private MyService myService;
@Test
public void testService() {
myService.performService();
}
}