今天是2025/0420 19:44 day 21
总路线请移步主页Java大纲相关文章
今天进行Spring 1,2,3 个模块的归纳
最近在忙毕设,更新有点慢,见谅
首先是Spring 的相关内容概括的思维导图
// 典型使用示例 ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); UserService userService = context.getBean(UserService.class);
方式 | 优点 | 缺点 |
---|---|---|
构造器注入 | 不可变对象,强依赖 | 参数多时代码臃肿 |
Setter注入 | 灵活性高 | 对象可能处于部分初始化状态 |
字段注入 | 代码简洁 | 难以测试,隐藏依赖关系 |
@Configuration public class AppConfig { @Bean public DataSource dataSource() { return new DriverManagerDataSource(...); } }
[业务组件] --交叉关注点--> [日志/事务/安全] \ / \ / [AOP代理层]
@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; } }
1. 实例化 → 2. 属性填充 → 3. BeanNameAware → 4. BeanFactoryAware ↓ 5. PreInitialization(BeanPostProcessor) → 6. @PostConstruct ↓ 7. InitializingBean → 8. 自定义init-method → 9. PostInitialization
@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
@Conditional(ProdEnvCondition.class) @Bean public DataSource prodDataSource() { return new ProductionDataSource(); } public class ProdEnvCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return "prod".equals(context.getEnvironment().getProperty("env")); } }
HTTP Request → DispatcherServlet → HandlerMapping → Controller → ModelAndView → ViewResolver → View → HTTP Response
@Controller @RequestMapping("/users") public class UserController { @GetMapping("/{id}") public String getUser(@PathVariable Long id, Model model) { model.addAttribute("user", userService.findById(id)); return "userDetail"; } }
@RestController @RequestMapping("/api/users") public class UserApiController { @PostMapping public ResponseEntitycreateUser(@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); } }
@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