Master Spring Boot 2.7: Bean Lifecycle, DI, AOP, Caching & More

This guide walks through essential Spring Boot 2.7.16 features—including bean lifecycle annotations, dependency injection methods, Java‑based configuration, conditional beans, event listeners, AOP, scheduled tasks, data access with Spring Data JPA, caching, exception handling, security, SpEL, configuration management, performance monitoring, and micro‑service components—providing concise code examples for each.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Master Spring Boot 2.7: Bean Lifecycle, DI, AOP, Caching & More

1. Bean Lifecycle

Use @PostConstruct and @PreDestroy to run code at specific bean lifecycle stages, or implement InitializingBean and DisposableBean interfaces.

public class Bean1 {
    @PostConstruct
    public void init() {}
    @PreDestroy
    public void destroy() {}
}

public class Bean2 implements InitializingBean, DisposableBean {
    public void afterPropertiesSet() {}
    public void destroy() {}
}

2. Dependency Injection

Automatic wiring with @Autowired.

Resolve ambiguity with @Qualifier.

Use @Resource or @Inject for injection.

@Component
public class Service {
    @Autowired
    private Dog dog;
    @Resource
    private Cat cat;
    @Autowired
    @Qualifier("d")
    private Person person;
    @Inject
    private DAO dao;
}

Constructor injection is recommended:

@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. Annotation‑Based Configuration

Replace XML with Java Config.

Use @Profile or other @Conditional mechanisms to provide environment‑specific beans.

@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();
    }
}

4. Conditional Bean Creation

Use @Conditional or Spring Boot’s @ConditionalOnMissingBean and @ConditionalOnProperty to create beans based on conditions.

@Bean
@ConditionalOnMissingBean(CsrfFilter.class)
@ConditionalOnProperty(prefix = "pack.csrf", name = "enabled", matchIfMissing = true)
public CsrfFilter csrfFilter() {
    return new CsrfFilter();
}

Custom condition example:

public class PackCondition implements Condition {
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // custom logic
        return true;
    }
}

@Component
@Conditional({PackCondition.class})
public class PersonServiceTest {}

5. Event Listening

Leverage Spring’s event mechanism for component communication.

Create custom events and listeners, either by implementing ApplicationListener or using @EventListener.

@Component
public class OrderListener implements ApplicationListener<OrderEvent> {
    public void onApplicationEvent(OrderEvent event) {
        // handle event
    }
}

@Configuration
public class EventManager {
    @EventListener
    public void order(OrderEvent event) {}
}

6. Aspect‑Oriented Programming (AOP)

Implement cross‑cutting concerns such as logging, security, or transaction management.

Define aspects, pointcuts, and advices.

@Component
@Aspect
public class AuthAspect {
    @Pointcut("execution(public * com.pack..*.*(..))")
    private void auth() {}

    @Before("auth()")
    public void before() {}
}

7. Scheduled Tasks

Use @Scheduled for simple cron‑based jobs.

Configure a TaskScheduler for more complex scheduling.

public class SchedueService {
    @Scheduled(cron = "*/2 * * * * *")
    public void task() {
        System.out.printf("%s: %d - 任务调度%n", Thread.currentThread().getName(), System.currentTimeMillis());
    }
}

@Bean
public ThreadPoolTaskScheduler taskScheduler() {
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setPoolSize(1);
    scheduler.initialize();
    return scheduler;
}

8. Data Access

Simplify persistence with Spring Data JPA.

Leverage repository interfaces for CRUD operations.

public interface OrderRepository extends JpaRepository<Order, Long>, JpaSpecificationExecutor<Order> {}
@Service
public class OrderDomainServiceImpl implements OrderDomainService {
    private final OrderRepository orderRepository;
    public OrderDomainServiceImpl(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }
    // CRUD methods
}

10. Caching

Use Spring Cache abstraction with annotations like @Cacheable and @CacheEvict.

Integrate third‑party caches such as EhCache or 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 {
    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager();
    }
}

11. Global Exception Handling

Use @ControllerAdvice and @ExceptionHandler to handle exceptions uniformly.

Return a consistent error response structure.

@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. Security Management

Integrate Spring Security for authentication and authorization, configuring URL patterns and role‑based access.

@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();
        return http.build();
    }
}

13. Spring Expression Language (SpEL)

Use SpEL for dynamic bean references, conditional logic, and integration with AOP.

14. Configuration Management

Spring Cloud Config for centralized configuration.

Spring Cloud Bus for dynamic updates.

In many projects, Nacos or Consul are preferred over native Spring Config.

15. Performance Monitoring

Integrate Spring Boot Admin for microservice monitoring.

Collect metrics with Micrometer or Prometheus.

16. Microservice Components

Build microservices with Spring Cloud.

Use OpenFeign for declarative HTTP calls.

Integrate Hystrix (or Resilience4j) for circuit breaking.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaMicroservicesaopcachingSpring Bootdependency-injection
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.