环境:SpringBoot2.7.16
1. Bean生命周期
使用@PostConstruct和@PreDestroy注解在Bean的生命周期特定阶段执行代码,也可以通过分别实现InitializingBean和DisposableBean接口。
public class Bean1 {@PostConstructpublic void init() {}@PreDestroypublic void destroy() {}}public class Bean2 implements InitializingBean, DisposableBean {public void afterPropertiesSet() {}public void destroy() {}}
2. 依赖注入
使用@Autowired注解自动装配Bean。
使用@Qualifier注解解决自动装配时的歧义。
使用@Resource或@Inject注解进行依赖注入。
@Componentpublic class Service {@Autowiredprivate Dog dog ;@Resourceprivate Cat cat ;@Autowired@Qualifier("d") // 指定beanNameprivate Person person ;@Injectprivate DAO dao ;}
以上都是基于属性的注入,官方建议使用构造函数注入
@Componentpublic 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功能为不同环境提供不同的配置。
@Configurationpublic class AppConfig {@Beanpublic 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接口自定义条件。
// 当前环境没有CsrfFilter Bean(CsrfFilter.class)// 配置文件中的pack.csrf.enabled=true或者没有配置(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的事件机制进行组件间的通信。
创建自定义事件和应用监听器。
@Componentpublic class OrderListener implements ApplicationListener<OrderEvent> {public void onApplicationEvent(OrderEvent event) {// ...}}// 也可以通过注解的方式@Configurationpublic class EventManager {@EventListenerpublic void order(OrderEvent event) {}}
事件详细使用,查看《利用Spring事件机制:打造可扩展和可维护的应用》。
6. 切面编程(AOP)
使用AOP实现横切关注点,如日志、权限、事务管理等。
定义切面、通知、切入点等。
@Component@Aspectpublic 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执行任务。
@Beanpublic 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操作了。
@Servicepublic 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@Configurationpublic class Config {// 配置基于内存的缓存管理器;你也可以使用基于redis的实现@Beanpublic CacheManager cacheManager() {ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager();return cacheManager ;}}
11.异常处理
使用@ControllerAdvice和@ExceptionHandler全局处理异常。
定义统一的异常响应格式。
@RestControllerAdvicepublic 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 {@Beanpublic 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表达式的应用。
玩转Spring表达式语言SpEL:在项目实践中与AOP的巧妙结合
通过Spring AOP结合SpEL表达式:构建强大且灵活的权限控制体系
14. 配置管理
使用Spring Cloud Config实现配置中心化管理。
集成Spring Cloud Bus实现配置动态更新。
我们项目中应该很少使用上面Spring 原生的 Config。现在大多使用的nacos或者consul。
15. 性能监控
集成Spring Boot Admin进行微服务监控。
使用Metrics或Micrometer进行应用性能指标收集。
有关性能监控的查看下面两篇文章:
在SpringBoot中如何通过Prometheus实时监控系统各项指标
以上2篇文章详细的介绍了有关服务监控的内容。
16. 微服务组件
利用Spring Cloud构建微服务架构。
使用Feign声明式地调用其他微服务。
集成Hystrix实现熔断和降级。
以上内容查看下面几篇文章,分别详细的介绍了每种组件的应用。
Spring Cloud 远程接口调用OpenFeign负载均衡实现原理详解
深入ReactiveFeign:反应式远程接口调用的最佳实践
以上是本篇文章的全部内容,希望对你有所帮助。



