πΉ 1. SpEL (Spring Expression Language)
β Definition:
SpEL is a powerful expression language used in Spring for querying and manipulating object graphs at runtime. It’s commonly used inside @Value
, XML, or annotation-based configuration to dynamically inject values.
β Basic Example:
@Component
public class MyComponent {
@Value("#{2 * 2}")
private int result;
@Value("#{T(Math).sqrt(25)}")
private double squareRoot;
@Value("#{myBean.name}")
private String injectedName;
}
Assume myBean
is another Spring-managed bean:
@Component("myBean")
public class MyBean {
public String name = "Ved";
}
β Explanation:
@Value("#{2 * 2}")
β Injects the result4
.T(Math).sqrt(25)
β CallsMath.sqrt(25)
β Result:5.0
.#{myBean.name}
β Injects thename
property from the bean namedmyBean
.
β Use Cases:
- Dynamic default values
- Reading system properties
- Accessing other beans’ fields or methods
πΉ 2. @Scheduled (Task Scheduling)
β Definition:
Springβs @Scheduled
annotation allows you to execute methods on a schedule, like a cron job or fixed interval.
β Example:
@Component
public class MyScheduler {
// Runs every 5 seconds
@Scheduled(fixedRate = 5000)
public void poll() {
System.out.println("Polling at " + new Date());
}
}
β Enable Scheduling:
To make @Scheduled
work, add this to a config class:
@Configuration
@EnableScheduling
public class AppConfig {}
β Explanation:
fixedRate = 5000
β Runs the method every 5 seconds, regardless of previous execution time.- Alternative attributes:
fixedDelay = 5000
: Runs after the previous call is completed + 5 seconds.cron = "0 0/1 * * * *"
: Runs every 1 minute (cron format).
β Use Cases:
- Polling APIs
- Auto-backups
- Regular cleanup tasks
πΉ 3. @Cacheable (Caching Results)
β Definition:
@Cacheable
marks a method so that Spring will cache the result of the method. If the same method is called with the same arguments again, Spring returns the cached result instead of executing the method again.
β Example:
@Service
public class UserService {
@Cacheable("users")
public User findById(String id) {
simulateSlowService();
return new User(id, "Ved");
}
private void simulateSlowService() {
try {
Thread.sleep(3000); // Simulate slow DB call
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
β Enable Caching:
@Configuration
@EnableCaching
public class CacheConfig {
// Configure your cache manager (e.g., ConcurrentMapCacheManager)
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("users");
}
}
β Explanation:
- First call to
findById("123")
β Takes 3 seconds and result is cached. - Second call to
findById("123")
β Returns immediately from cache.
β Use Cases:
- Reducing DB calls
- Caching expensive calculations
- Performance optimization for read-heavy apps
π Summary Table:
Concept | Purpose | Key Annotation |
---|---|---|
SpEL | Dynamically inject values | @Value("#{...}") |
@Scheduled | Run methods periodically | @Scheduled |
@Cacheable | Cache method return values | @Cacheable |