注解配置
注解配置是Spring 2.5引入的配置方式,通过注解在代码中直接定义Bean和依赖关系。
Bean定义注解
@Component
通用组件注解,任何类都可使用。
Java
@Component
public class CommonComponent {
}
@Service
业务层组件,语义更明确。
Java
@Service
public class UserService {
public void save(User user) {
// 业务逻辑
}
}
@Repository
数据访问层组件,支持异常转换。
Java
@Repository
public class UserRepository {
public User findById(Long id) {
// 数据访问
}
}
@Controller
控制器层组件,用于Web应用。
Java
@Controller
public class UserController {
@RequestMapping("/users")
public String list() {
return "userList";
}
}
@RestController
RESTful控制器,相当于@Controller + @ResponseBody。
Java
@RestController
public class UserApiController {
@GetMapping("/api/users")
public List<User> list() {
return userService.findAll();
}
}
四种组件注解对比
| 注解 | 层级 | 作用 |
|---|---|---|
| @Component | 通用 | 通用组件 |
| @Service | Service层 | 业务服务 |
| @Repository | DAO层 | 数据访问 |
| @Controller | Controller层 | Web控制器 |
四种注解功能相同,只是语义区分,便于分层管理。
依赖注入注解
@Autowired
Java
@Service
public class OrderService {
// 字段注入
@Autowired
private UserService userService;
// 构造器注入(推荐)
private final PaymentService paymentService;
@Autowired
public OrderService(PaymentService paymentService) {
this.paymentService = paymentService;
}
// Setter注入
@Autowired
public void setNotificationService(NotificationService service) {
this.notificationService = service;
}
}
@Qualifier
Java
@Service
public class OrderService {
@Autowired
@Qualifier("primaryPaymentService")
private PaymentService paymentService;
}
@Resource
Java
@Service
public class OrderService {
@Resource
private UserService userService;
@Resource(name = "primaryService")
private PaymentService paymentService;
}
配置类注解
@Configuration
Java
@Configuration
public class AppConfig {
@Bean
public UserService userService() {
return new UserService();
}
}
@ComponentScan
Java
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
}
// 等价于XML: <context:component-scan base-package="com.example"/>
@EnableAspectJAutoProxy
Java
@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
}
开启注解扫描
Java配置
Java
@Configuration
@ComponentScan("com.example")
public class AppConfig {
}
XML配置
XML
<context:component-scan base-package="com.example"/>
Spring Boot
Java
@SpringBootApplication // 已包含@ComponentScan
public class Application {
}
注解配置优缺点
| 优点 | 缺点 |
|---|---|
| 代码简洁 | 配置分散在代码中 |
| 类型安全 | 修改需重新编译 |
| IDE支持好 | 不适合集中管理 |
| 符合现代习惯 | 与代码耦合 |
常用注解一览
| 注解 | 作用 |
|---|---|
| @Component | 定义Bean |
| @Service | 业务层Bean |
| @Repository | 数据层Bean |
| @Controller | 控制层Bean |
| @Autowired | 依赖注入 |
| @Qualifier | 指定Bean名称 |
| @Resource | JSR-250注入 |
| @Scope | 定义作用域 |
| @Lazy | 懒加载 |
| @Primary | 优先注入 |
要点总结
- @Component/@Service/@Repository/@Controller用于定义Bean
- 四种注解功能相同,只是语义区分
- @Autowired按类型注入,@Resource按名称注入
- @ComponentScan开启注解扫描
- Spring Boot默认扫描主类所在包及其子包
📝 发现内容有误?点击此处直接编辑