环境:SpringBoot2.7.16
1. Bean生命周期
使用@PostConstruct和@PreDestroy注解在Bean的生命周期特定阶段执行代码,也可以通过分别实现InitializingBean和DisposableBean接口。
public class Bean1 { @PostConstruct public void init() {} @PreDestroy public void destroy() {} } public class Bean2 implements InitializingBean, DisposableBean { public void afterPropertiesSet() {} public void destroy() {} }
2. 依赖注入
- 使用@Autowired注解自动装配Bean。
- 使用@Qualifier注解解决自动装配时的歧义。
- 使用@Resource或@Inject注解进行依赖注入。
@Component public class Service { @Autowired private Dog dog ; @Resource private Cat cat ; @Autowired @Qualifier("d") // 指定beanName private Person person ; @Inject private DAO dao ; }
以上都是基于属性的注入,官方建议使用构造函数注入
@Component public class Service { private final Dog dog ; private final Cat cat ; public Service(Dog dog, Cat cat) { this.dog = dog ; this.cat = cat ; } }
3. 基于注解配置
- 使用Java Config替代传统的XML配置。
- 利用Profile或是各种Conditional功能为不同环境提供不同的配置。
@Configuration public class AppConfig { @Bean public PersonService personService(PersonDAO dao) { return new PersonService(dao) ; } @Bean @Profile("test") public PersonDAO personDAOTest() { return new PersonDAOTest() ; } @Bean @Profile("prod") public PersonDAO personDAOProd() { return new PersonDAOProd() ; } }
上面的@Profile会根据当前环境配置的spring.profiles.active属性决定创建那个对象。
4. 条件配置Bean
- 使用@Conditional注解根据条件创建Bean。
- 实现Condition接口自定义条件。
@Bean // 当前环境没有CsrfFilter Bean @ConditionalOnMissingBean(CsrfFilter.class) // 配置文件中的pack.csrf.enabled=true或者没有配置 @ConditionalOnProperty(prefix = "pack.csrf", name = "enabled", matchIfMissing = true) public CsrfFilter csrfFilter() { return new CsrfFilter (); }
自定义条件配置
public class PackCondition implements Condition { public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { // ... } } // 使用 @Component @Conditional({PackCondition.class}) public class PersonServiceTest {}
5. 事件监听
- 使用Spring的事件机制进行组件间的通信。
- 创建自定义事件和应用监听器。
@Component public class OrderListener implements ApplicationListener<OrderEvent> { public void onApplicationEvent(OrderEvent event) { // ... } } // 也可以通过注解的方式 @Configuration public class EventManager { @EventListener public void order(OrderEvent event) {} }
事件详细使用,查看《利用Spring事件机制:打造可扩展和可维护的应用》。
6. 切面编程(AOP)
- 使用AOP实现横切关注点,如日志、权限、事务管理等。
- 定义切面、通知、切入点等。
@Component @Aspect public class AuthAspect { @Pointcut("execution(public * com.pack..*.*(..))") private void auth() {} @Before("auth()") public void before() { } }
7. 计划任务
- 使用@Scheduled注解轻松实现定时任务。
- 配置TaskScheduler进行更复杂的任务调度。
public class SchedueService { @Scheduled(cron = "*/2 * * * * *") public void task() { System.out.printf("%s: %d - 任务调度%n", Thread.currentThread().getName(), System.currentTimeMillis()) ; } }
每隔2s执行任务。
@Bean public ThreadPoolTaskScheduler taskScheduler() { ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler(); threadPoolTaskScheduler.setPoolSize(1) ; threadPoolTaskScheduler.initialize() ; return threadPoolTaskScheduler ; }
自定义线程池任务调度。
8. 数据访问
- 用Spring Data JPA简化数据库访问层的开发。
- 利用Spring Data Repositories的声明式方法实现CRUD操作。
public interface OrderRepository extends JpaRepository<Order, Long>, JpaSpecificationExecutor<Order> { }
通过继承JapRepository等类就可以直接对数据库进行CRUD操作了。
@Service public class OrderDomainServiceImpl implements OrderDomainService { private final OrderRepository orderRepository; public OrderDomainServiceImpl(OrderRepository orderRepository) { this.orderRepository = orderRepository; } // CRUD操作 }
OrderRepository接口提供了如下方法,我们可以直接的调用
图片
10. 缓存使用
- 使用Spring Cache抽象进行缓存操作。
- 集成第三方缓存库,如EhCache、Redis等。
public class UserService { @Cacheable(cacheNames = "users", key = "#id") public User queryUserById(Integer id) { System.out.println("查询操作") ; return new User() ; } @CacheEvict(cacheNames = "users", key = "#user.id") public void update(User user) { System.out.println("更新操作") ; } } @EnableCaching @Configuration public class Config { // 配置基于内存的缓存管理器;你也可以使用基于redis的实现 @Bean public CacheManager cacheManager() { ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(); return cacheManager ; } }
11.异常处理
- 使用@ControllerAdvice和@ExceptionHandler全局处理异常。
- 定义统一的异常响应格式。
@RestControllerAdvice public class PackControllerAdvice { @ExceptionHandler({Exception.class}) public Object error(Exception e) { Map<String, Object> errors = new HashMap<>() ; errors.put("error", e.getMessage()) ; return errors ; } }
当应用发生异常后会统一的由上面的类进行处理。
12. 安全管理
集成Spring Security进行身份验证和授权。通过引入spring security进行简单的配置就能非常方便的管理应用的权限控制。
@Configuration @EnableGlobalMethodSecurity(jsr250Enabled = true, prePostEnabled = true, securedEnabled = true) public class SecurityConfig { @Bean public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception { http.csrf().disable() ; http.authorizeRequests().antMatchers("/*.html").permitAll() ; http.authorizeRequests().antMatchers("/customers/**").hasAnyRole("CUSTOM") ; http.authorizeRequests().antMatchers("/orders/**").hasAnyRole("ORDER") ; http.authorizeRequests().anyRequest().authenticated() ; http.formLogin() ; DefaultSecurityFilterChain chain = http.build(); return chain ; } }
注意:Spring Security从5.7?开始建议使用SecurityFilterChain方式配置授权规则。
13. SpEL表达式
利用Spring Expression Language (SpEL)进行表达式求值,动态调用bean等等功能。
详细查看下面文章,这篇文章详细的介绍了SpEL表达式的应用。
14. 配置管理
- 使用Spring Cloud Config实现配置中心化管理。
- 集成Spring Cloud Bus实现配置动态更新。
我们项目中应该很少使用上面Spring 原生的 Config。现在大多使用的nacos或者consul。
15. 性能监控
- 集成Spring Boot Admin进行微服务监控。
- 使用Metrics或Micrometer进行应用性能指标收集。
16. 微服务组件
- 利用Spring Cloud构建微服务架构。
- 使用Feign声明式地调用其他微服务。
- 集成Hystrix实现熔断和降级。
以上内容查看下面几篇文章,分别详细的介绍了每种组件的应用。
原文地址:https://mp.weixin.qq.com/s/HLhbd6Sd8DypRE1MvVKEAg