今天是2025/0420 19:44 day 21
总路线请移步主页Java大纲相关文章
今天进行Spring 1,2,3 个模块的归纳
最近在忙毕设,更新有点慢,见谅
首先是Spring 的相关内容概括的思维导图
一、核心概念详解
1. IoC容器
1.1 工作原理
// 典型使用示例 ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); UserService userService = context.getBean(UserService.class);
1.2 依赖注入方式对比
方式 | 优点 | 缺点 |
---|---|---|
构造器注入 | 不可变对象,强依赖 | 参数多时代码臃肿 |
Setter注入 | 灵活性高 | 对象可能处于部分初始化状态 |
字段注入 | 代码简洁 | 难以测试,隐藏依赖关系 |
1.3 注解驱动开发
@Configuration public class AppConfig {@Bean public DataSource dataSource() {return new DriverManagerDataSource(...);} }
2. AOP编程
2.1 核心概念图解
[业务组件] --交叉关注点--> [日志/事务/安全]\ /\ /[AOP代理层]
2.2 通知类型示例
@Aspect public class LogAspect {@Before("execution(* com.example.service.*.*(..))")public void logBefore(JoinPoint jp) {System.out.println("方法调用前: " + jp.getSignature());}@Around("@annotation(com.example.Monitor)")public Object monitorPerformance(ProceedingJoinPoint pjp) throws Throwable {long start = System.currentTimeMillis();Object result = pjp.proceed();System.out.println("方法执行耗时: " + (System.currentTimeMillis()-start));return result;} }
二、Spring容器深度解析
1. Bean生命周期全流程
1. 实例化 → 2. 属性填充 → 3. BeanNameAware → 4. BeanFactoryAware↓ 5. PreInitialization(BeanPostProcessor) → 6. @PostConstruct↓ 7. InitializingBean → 8. 自定义init-method → 9. PostInitialization
2. 作用域对比实验
@Scope("prototype") @Bean public PrototypeBean pb() { return new PrototypeBean(); } // 测试代码: PrototypeBean b1 = context.getBean(PrototypeBean.class); PrototypeBean b2 = context.getBean(PrototypeBean.class); System.out.println(b1 == b2); // 输出false
3. 条件化配置
@Conditional(ProdEnvCondition.class) @Bean public DataSource prodDataSource() {return new ProductionDataSource(); } public class ProdEnvCondition implements Condition {@Overridepublic boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {return "prod".equals(context.getEnvironment().getProperty("env"));} }
三、Spring MVC全流程剖析
1. 请求处理时序图
HTTP Request → DispatcherServlet → HandlerMapping → Controller → ModelAndView → ViewResolver → View → HTTP Response
2. 控制器开发模式
2.1 传统控制器
@Controller @RequestMapping("/users") public class UserController {@GetMapping("/{id}")public String getUser(@PathVariable Long id, Model model) {model.addAttribute("user", userService.findById(id));return "userDetail";} }
2.2 RESTful风格
@RestController @RequestMapping("/api/users") public class UserApiController { @PostMappingpublic ResponseEntity<User> createUser(@RequestBody @Valid User user) {User saved = userService.save(user);URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(saved.getId()).toUri();return ResponseEntity.created(location).body(saved);} }
3. 异常处理机制
@ControllerAdvice public class GlobalExceptionHandler {@ExceptionHandler(DataNotFoundException.class)@ResponseStatus(HttpStatus.NOT_FOUND)public ErrorResponse handleNotFound(DataNotFoundException ex) {return new ErrorResponse("NOT_FOUND", ex.getMessage());}@ExceptionHandler(MethodArgumentNotValidException.class)public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {Map<String, String> errors = new HashMap<>();ex.getBindingResult().getAllErrors().forEach(error -> {String fieldName = ((FieldError) error).getField();errors.put(fieldName, error.getDefaultMessage());});return ResponseEntity.badRequest().body(errors);} }