Spring Context module providing application context and dependency injection capabilities
npx @tessl/cli install tessl/maven-org-springframework--spring-context@6.2.0Spring Context is the core module of the Spring Framework that provides comprehensive application context and dependency injection capabilities. It implements the Inversion of Control (IoC) container that manages object lifecycle, dependency resolution, and bean configuration through annotations, XML, or Java-based configuration. The module supports advanced features including aspect-oriented programming integration, event handling, internationalization, validation, scheduled task execution, and integration with Jakarta EE specifications.
pom.xml:<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.2.8</version>
</dependency>For Gradle build.gradle:
implementation 'org.springframework:spring-context:6.2.8'import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Repository;
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;
// Configuration class
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
@Bean
public UserService userService() {
return new UserService();
}
}
// Service component
@Service
public class UserService {
public String getUser() {
return "John Doe";
}
}
// Application startup
public class Application {
public static void main(String[] args) {
// Create application context
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
// Retrieve beans
UserService userService = context.getBean(UserService.class);
String user = userService.getUser();
System.out.println("User: " + user);
// Close context (if configurable)
if (context instanceof ConfigurableApplicationContext) {
((ConfigurableApplicationContext) context).close();
}
}
}Spring Context is built around several key architectural components:
Core ApplicationContext interfaces and implementations providing the foundation for dependency injection and application configuration. Includes context lifecycle management, hierarchical contexts, and various implementation strategies.
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory,
HierarchicalBeanFactory, MessageSource, ApplicationEventPublisher, ResourcePatternResolver {
String getId();
String getApplicationName();
String getDisplayName();
long getStartupDate();
ApplicationContext getParent();
AutowireCapableBeanFactory getAutowireCapableBeanFactory();
}
public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {
void setId(String id);
void setParent(ApplicationContext parent);
void setEnvironment(ConfigurableEnvironment environment);
void refresh();
void registerShutdownHook();
void close();
boolean isActive();
ConfigurableListableBeanFactory getBeanFactory();
}Annotation-driven configuration including @Configuration classes, @Bean methods, component scanning, and import mechanisms. Provides the foundation for modern Java-based Spring configuration.
@Configuration
public @interface Configuration {
String value() default "";
boolean proxyBeanMethods() default true;
boolean enforceUniqueMethods() default true;
}
@Bean
public @interface Bean {
String[] value() default {};
String[] name() default {};
String initMethod() default "";
String destroyMethod() default "";
}
@ComponentScan
public @interface ComponentScan {
String[] value() default {};
String[] basePackages() default {};
Class<?>[] basePackageClasses() default {};
boolean useDefaultFilters() default true;
}IoC container functionality including bean definitions, autowiring, scope management, and dependency resolution. Covers both programmatic and declarative approaches to dependency injection.
public interface BeanFactory {
Object getBean(String name);
<T> T getBean(String name, Class<T> requiredType);
<T> T getBean(Class<T> requiredType);
boolean containsBean(String name);
boolean isSingleton(String name);
boolean isPrototype(String name);
}
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Autowired {
boolean required() default true;
}Application event system with @EventListener annotations, event publishing, and multicasting. Supports synchronous and asynchronous event processing with conditional handling.
@EventListener
public @interface EventListener {
Class<?>[] classes() default {};
String condition() default "";
String id() default "";
}
public interface ApplicationEventPublisher {
default void publishEvent(ApplicationEvent event) {}
default void publishEvent(Object event) {}
}
public abstract class ApplicationEvent extends EventObject {
public final long getTimestamp() {}
}Task scheduling and asynchronous execution with @Scheduled and @Async annotations. Includes task schedulers, executors, and timing configuration options.
@Scheduled
public @interface Scheduled {
String cron() default "";
String zone() default "";
long fixedDelay() default -1;
long fixedRate() default -1;
long initialDelay() default -1;
TimeUnit timeUnit() default TimeUnit.MILLISECONDS;
}
@Async
public @interface Async {
String value() default "";
}
public interface TaskScheduler {
ScheduledFuture<?> schedule(Runnable task, Trigger trigger);
ScheduledFuture<?> schedule(Runnable task, Instant startTime);
ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period);
}Declarative caching with @Cacheable, @CachePut, and @CacheEvict annotations. Includes cache managers, key generation, and cache abstraction layer.
@Cacheable
public @interface Cacheable {
String[] value() default {};
String[] cacheNames() default {};
String key() default "";
String condition() default "";
String unless() default "";
boolean sync() default false;
}
public interface Cache {
String getName();
Object getNativeCache();
ValueWrapper get(Object key);
<T> T get(Object key, Class<T> type);
void put(Object key, Object value);
void evict(Object key);
void clear();
}
public interface CacheManager {
Cache getCache(String name);
Collection<String> getCacheNames();
}Bean validation and data binding with JSR-303/349 integration, Validator interfaces, and error handling. Supports both programmatic and declarative validation.
public interface Validator {
boolean supports(Class<?> clazz);
void validate(Object target, Errors errors);
}
public interface SmartValidator extends Validator {
void validate(Object target, Errors errors, Object... validationHints);
default void validateValue(Class<?> targetType, String fieldName, Object value,
Errors errors, Object... validationHints) {}
}
@Validated
public @interface Validated {
Class<?>[] value() default {};
}Type conversion and formatting with Formatter interfaces, @DateTimeFormat and @NumberFormat annotations. Handles conversion between strings and objects for web binding.
public interface Formatter<T> extends Printer<T>, Parser<T> {
String print(T object, Locale locale);
T parse(String text, Locale locale);
}
@DateTimeFormat
public @interface DateTimeFormat {
String style() default "SS";
ISO iso() default ISO.NONE;
String pattern() default "";
String[] fallbackPatterns() default {};
}
@NumberFormat
public @interface NumberFormat {
Style style() default Style.DEFAULT;
String pattern() default "";
}Bean lifecycle management including initialization, destruction, startup/shutdown phases, and lifecycle callbacks. Provides fine-grained control over component lifecycle.
public interface Lifecycle {
void start();
void stop();
boolean isRunning();
}
public interface SmartLifecycle extends Lifecycle, Phased {
default boolean isAutoStartup() { return true; }
default void stop(Runnable callback) { stop(); callback.run(); }
default int getPhase() { return DEFAULT_PHASE; }
}
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
public interface DisposableBean {
void destroy() throws Exception;
}Environment abstraction and property source management including profiles, property resolution, and @ConfigurationProperties binding for type-safe configuration.
public interface Environment extends PropertyResolver {
String[] getActiveProfiles();
String[] getDefaultProfiles();
boolean acceptsProfiles(Profiles profiles);
}
public interface ConfigurableEnvironment extends Environment, ConfigurablePropertyResolver {
void setActiveProfiles(String... profiles);
void addActiveProfile(String profile);
void setDefaultProfiles(String... profiles);
MutablePropertySources getPropertySources();
}
@ConfigurationProperties
public @interface ConfigurationProperties {
String value() default "";
String prefix() default "";
boolean ignoreInvalidFields() default false;
boolean ignoreUnknownFields() default true;
}