0
# Spring Integration
1
2
Deep Spring Framework integration providing application context management, conditional beans, configuration properties, Spring Boot support, and custom conditions for CAS applications.
3
4
## ApplicationContextProvider
5
6
Central provider for Spring application context access and bean management throughout the CAS system.
7
8
```java { .api }
9
public class ApplicationContextProvider implements ApplicationContextAware {
10
11
// Core context access
12
public static ApplicationContext getApplicationContext();
13
public static ConfigurableApplicationContext getConfigurableApplicationContext();
14
15
// ApplicationContextAware implementation
16
@Override
17
public void setApplicationContext(ApplicationContext context) throws BeansException;
18
19
// Static context management
20
public static void holdApplicationContext(ApplicationContext ctx);
21
22
// Bean injection and processing
23
public static void processBeanInjections(Object bean);
24
25
// Bean registration
26
public static <T> T registerBeanIntoApplicationContext(
27
ApplicationContext applicationContext,
28
T object,
29
String name
30
);
31
32
public static <T> T registerBeanIntoApplicationContext(
33
ConfigurableApplicationContext applicationContext,
34
T object,
35
String name
36
);
37
38
// Bean retrieval utilities
39
public static <T> Optional<T> getBean(String name, Class<T> clazz);
40
public static <T> Optional<T> getBean(Class<T> clazz);
41
42
// CAS-specific utilities
43
public static Optional<CasConfigurationProperties> getCasConfigurationProperties();
44
public static Optional<ScriptResourceCacheManager<String, ExecutableCompiledScript>>
45
getScriptResourceCacheManager();
46
public static Optional<MessageSanitizer> getMessageSanitizer();
47
}
48
```
49
50
### Usage Examples
51
52
**Basic application context usage:**
53
```java
54
@Component
55
public class CasServiceImpl implements CasService {
56
57
public void performOperation() {
58
// Access application context
59
ApplicationContext context = ApplicationContextProvider.getApplicationContext();
60
61
// Get beans by type
62
Optional<UserService> userService = ApplicationContextProvider.getBean(UserService.class);
63
64
// Get beans by name and type
65
Optional<CacheManager> cacheManager =
66
ApplicationContextProvider.getBean("cacheManager", CacheManager.class);
67
68
// Access CAS configuration
69
Optional<CasConfigurationProperties> config =
70
ApplicationContextProvider.getCasConfigurationProperties();
71
72
if (config.isPresent()) {
73
processWithConfiguration(config.get());
74
}
75
}
76
77
public void registerDynamicBean() {
78
// Register beans at runtime
79
MyDynamicService service = new MyDynamicService();
80
ApplicationContextProvider.registerBeanIntoApplicationContext(
81
ApplicationContextProvider.getConfigurableApplicationContext(),
82
service,
83
"dynamicService"
84
);
85
}
86
}
87
```
88
89
**Bean injection in non-Spring managed classes:**
90
```java
91
public class NonSpringManagedClass {
92
93
@Autowired
94
private UserRepository userRepository;
95
96
@Autowired
97
private PasswordEncoder passwordEncoder;
98
99
public NonSpringManagedClass() {
100
// Inject Spring dependencies
101
ApplicationContextProvider.processBeanInjections(this);
102
}
103
104
public boolean authenticate(String username, String password) {
105
User user = userRepository.findByUsername(username);
106
return user != null && passwordEncoder.matches(password, user.getPasswordHash());
107
}
108
}
109
```
110
111
## Spring Boot Integration
112
113
### AbstractCasBanner
114
115
Abstract base for CAS application banners displayed during startup.
116
117
```java { .api }
118
public abstract class AbstractCasBanner implements Banner {
119
120
// Banner configuration
121
protected String title;
122
protected String version;
123
protected String description;
124
125
// Banner interface implementation
126
@Override
127
public void printBanner(Environment environment,
128
Class<?> sourceClass,
129
PrintStream printStream);
130
131
// Template method for customization
132
protected abstract String getBannerText();
133
protected String getTitle();
134
protected String getVersion();
135
protected String getDescription();
136
}
137
```
138
139
### CasBanner and DefaultCasBanner
140
141
Concrete banner implementations for CAS applications.
142
143
```java { .api }
144
public class CasBanner extends AbstractCasBanner {
145
146
public CasBanner();
147
148
@Override
149
protected String getBannerText();
150
}
151
152
public class DefaultCasBanner extends AbstractCasBanner {
153
154
public DefaultCasBanner();
155
156
@Override
157
protected String getBannerText();
158
}
159
```
160
161
### AbstractCasSpringBootServletInitializer
162
163
Abstract servlet initializer for CAS Spring Boot applications.
164
165
```java { .api }
166
public abstract class AbstractCasSpringBootServletInitializer
167
extends SpringBootServletInitializer {
168
169
// Servlet initialization
170
@Override
171
protected SpringApplicationBuilder configure(SpringApplicationBuilder application);
172
173
// Template methods for customization
174
protected abstract Class<?>[] getConfigurationClasses();
175
protected String[] getActiveProfiles();
176
protected Properties getDefaultProperties();
177
}
178
```
179
180
### Usage Examples
181
182
**Custom banner implementation:**
183
```java
184
@Component
185
public class CustomCasBanner extends AbstractCasBanner {
186
187
public CustomCasBanner() {
188
this.title = "My CAS Server";
189
this.version = "1.0.0";
190
this.description = "Custom CAS Implementation";
191
}
192
193
@Override
194
protected String getBannerText() {
195
return """
196
╔════════════════════════════════════╗
197
║ MY CAS SERVER ║
198
║ v1.0.0 ║
199
╚════════════════════════════════════╝
200
""";
201
}
202
}
203
204
@SpringBootApplication
205
public class MyCasApplication {
206
207
public static void main(String[] args) {
208
SpringApplication app = new SpringApplication(MyCasApplication.class);
209
app.setBanner(new CustomCasBanner());
210
app.run(args);
211
}
212
}
213
```
214
215
**Servlet initializer for WAR deployment:**
216
```java
217
public class CasWebApplicationInitializer extends AbstractCasSpringBootServletInitializer {
218
219
@Override
220
protected Class<?>[] getConfigurationClasses() {
221
return new Class<?>[] {
222
CasWebApplication.class,
223
CasSecurityConfiguration.class,
224
CasServicesConfiguration.class
225
};
226
}
227
228
@Override
229
protected String[] getActiveProfiles() {
230
return new String[] { "production", "ssl" };
231
}
232
233
@Override
234
protected Properties getDefaultProperties() {
235
Properties props = new Properties();
236
props.setProperty("server.port", "8443");
237
props.setProperty("server.ssl.enabled", "true");
238
return props;
239
}
240
}
241
```
242
243
## Conditional Annotations and Conditions
244
245
### Feature-Based Conditions
246
247
```java { .api }
248
@Target({ElementType.TYPE, ElementType.METHOD})
249
@Retention(RetentionPolicy.RUNTIME)
250
@Conditional(CasFeatureEnabledCondition.class)
251
public @interface ConditionalOnFeatureEnabled {
252
253
// Feature name to check
254
String feature();
255
256
// Module name (optional)
257
String module() default "";
258
259
// Enabled by default
260
boolean enabledByDefault() default true;
261
}
262
263
@Target({ElementType.TYPE, ElementType.METHOD})
264
@Retention(RetentionPolicy.RUNTIME)
265
@Conditional(CasFeatureEnabledCondition.class)
266
public @interface ConditionalOnFeaturesEnabled {
267
268
// Multiple features (AND logic)
269
ConditionalOnFeatureEnabled[] value();
270
}
271
```
272
273
### Hostname-Based Conditions
274
275
```java { .api }
276
@Target({ElementType.TYPE, ElementType.METHOD})
277
@Retention(RetentionPolicy.RUNTIME)
278
@Conditional(MatchingHostnameCondition.class)
279
public @interface ConditionalOnMatchingHostname {
280
281
// Hostname patterns to match
282
String[] value();
283
284
// Use regex matching
285
boolean regex() default false;
286
}
287
```
288
289
### GraalVM Native Image Conditions
290
291
```java { .api }
292
@Target({ElementType.TYPE, ElementType.METHOD})
293
@Retention(RetentionPolicy.RUNTIME)
294
@Conditional(CasGraalVMNativeImageDisabledCondition.class)
295
public @interface ConditionalOnMissingGraalVMNativeImage {
296
}
297
```
298
299
### Usage Examples
300
301
**Feature-based conditional configuration:**
302
```java
303
@Configuration
304
public class ConditionalConfiguration {
305
306
@Bean
307
@ConditionalOnFeatureEnabled(feature = "multifactor-authentication")
308
public MultiFactorAuthenticationProvider mfaProvider() {
309
return new DefaultMultiFactorAuthenticationProvider();
310
}
311
312
@Bean
313
@ConditionalOnFeaturesEnabled({
314
@ConditionalOnFeatureEnabled(feature = "ldap"),
315
@ConditionalOnFeatureEnabled(feature = "authentication")
316
})
317
public LdapAuthenticationHandler ldapAuthHandler() {
318
return new LdapAuthenticationHandler();
319
}
320
321
@Bean
322
@ConditionalOnMatchingHostname({"*.example.com", "cas-prod-*"})
323
public ProductionSecurityConfiguration prodSecurityConfig() {
324
return new ProductionSecurityConfiguration();
325
}
326
327
@Bean
328
@ConditionalOnMissingGraalVMNativeImage
329
public ReflectionBasedService reflectionService() {
330
// Only available in JVM mode, not in native image
331
return new ReflectionBasedService();
332
}
333
}
334
```
335
336
## Bean Management Utilities
337
338
### BeanSupplier Interface
339
340
Supplier interface for conditional bean creation with enhanced features.
341
342
```java { .api }
343
public interface BeanSupplier<T> extends Supplier<T> {
344
345
// Enhanced supply methods
346
T supply();
347
T supply(Supplier<T> defaultSupplier);
348
349
// Conditional operations
350
BeanSupplier<T> ifAvailable();
351
BeanSupplier<T> ifMissing();
352
BeanSupplier<T> when(BeanCondition condition);
353
354
// Factory methods
355
static <T> BeanSupplier<T> of(Supplier<T> supplier);
356
static <T> BeanSupplier<T> ofBean(Class<T> beanType);
357
static <T> BeanSupplier<T> ofBean(String beanName, Class<T> beanType);
358
}
359
```
360
361
### BeanContainer Interface
362
363
Container interface for managing bean collections.
364
365
```java { .api }
366
public interface BeanContainer<T> {
367
368
// Container operations
369
Collection<T> toCollection();
370
List<T> toList();
371
Set<T> toSet();
372
373
// Filtering operations
374
BeanContainer<T> filter(Predicate<T> predicate);
375
<R> BeanContainer<R> map(Function<T, R> mapper);
376
377
// Conditional operations
378
BeanContainer<T> ifAvailable();
379
BeanContainer<T> ifNotEmpty();
380
381
// Factory methods
382
static <T> BeanContainer<T> of(Collection<T> beans);
383
static <T> BeanContainer<T> ofType(Class<T> beanType);
384
}
385
```
386
387
### Usage Examples
388
389
**Advanced bean management:**
390
```java
391
@Service
392
public class DynamicBeanService {
393
394
public void configureDynamicBeans() {
395
// Conditional bean supply
396
AuthenticationHandler handler = BeanSupplier
397
.ofBean("ldapAuthHandler", AuthenticationHandler.class)
398
.ifAvailable()
399
.supply(() -> new DefaultAuthenticationHandler());
400
401
// Bean container operations
402
List<AuthenticationHandler> handlers = BeanContainer
403
.ofType(AuthenticationHandler.class)
404
.filter(h -> h.supports(UsernamePasswordCredential.class))
405
.toList();
406
407
// Conditional bean creation
408
CacheManager cacheManager = BeanSupplier
409
.ofBean(CacheManager.class)
410
.when(environment -> environment.getProperty("cache.enabled", Boolean.class, false))
411
.supply(() -> new InMemoryCacheManager());
412
}
413
}
414
```
415
416
## Spring Utilities
417
418
### DirectObjectProvider
419
420
Direct object provider implementation for dependency injection.
421
422
```java { .api }
423
public class DirectObjectProvider<T> implements ObjectProvider<T> {
424
425
public DirectObjectProvider(T object);
426
427
@Override
428
public T getObject() throws BeansException;
429
430
@Override
431
public T getObject(Object... args) throws BeansException;
432
433
@Override
434
public T getIfAvailable() throws BeansException;
435
436
@Override
437
public T getIfUnique() throws BeansException;
438
439
@Override
440
public Stream<T> stream();
441
442
@Override
443
public Iterator<T> iterator();
444
}
445
```
446
447
### SpringExpressionLanguageValueResolver
448
449
SpEL (Spring Expression Language) value resolver for dynamic property resolution.
450
451
```java { .api }
452
public class SpringExpressionLanguageValueResolver {
453
454
// Expression evaluation
455
public Object evaluate(String expression, Map<String, Object> variables);
456
public <T> T evaluate(String expression, Class<T> resultType);
457
public <T> T evaluate(String expression,
458
Map<String, Object> variables,
459
Class<T> resultType);
460
461
// Template-based evaluation
462
public String evaluateTemplate(String template, Map<String, Object> variables);
463
464
// Utility methods
465
public boolean isExpression(String value);
466
public static SpringExpressionLanguageValueResolver getInstance();
467
}
468
```
469
470
### SecurityContextUtils
471
472
Security context utilities for authentication and authorization operations.
473
474
```java { .api }
475
@UtilityClass
476
public class SecurityContextUtils {
477
478
// Authentication access
479
public static Authentication getAuthentication();
480
public static Optional<Authentication> getCurrentAuthentication();
481
482
// Principal access
483
public static Object getPrincipal();
484
public static <T> T getPrincipal(Class<T> type);
485
public static String getUsername();
486
487
// Authority checking
488
public static boolean hasRole(String role);
489
public static boolean hasAuthority(String authority);
490
public static boolean hasAnyRole(String... roles);
491
public static boolean hasAnyAuthority(String... authorities);
492
493
// Context management
494
public static void setAuthentication(Authentication authentication);
495
public static void clearContext();
496
}
497
```
498
499
### Usage Examples
500
501
**SpEL integration for dynamic configuration:**
502
```java
503
@Component
504
public class DynamicConfigurationService {
505
506
private final SpringExpressionLanguageValueResolver spelResolver;
507
508
public DynamicConfigurationService() {
509
this.spelResolver = SpringExpressionLanguageValueResolver.getInstance();
510
}
511
512
public String resolveConfigValue(String configExpression, User user) {
513
Map<String, Object> context = Map.of(
514
"user", user,
515
"env", System.getenv(),
516
"props", System.getProperties()
517
);
518
519
if (spelResolver.isExpression(configExpression)) {
520
return spelResolver.evaluate(configExpression, context, String.class);
521
}
522
523
return configExpression;
524
}
525
526
public boolean evaluateCondition(String condition, HttpServletRequest request) {
527
Map<String, Object> context = Map.of(
528
"request", request,
529
"headers", Collections.list(request.getHeaderNames()),
530
"params", request.getParameterMap()
531
);
532
533
return spelResolver.evaluate(condition, context, Boolean.class);
534
}
535
}
536
```
537
538
**Security context operations:**
539
```java
540
@RestController
541
public class SecureApiController {
542
543
@GetMapping("/api/user-info")
544
public ResponseEntity<?> getUserInfo() {
545
// Get current authentication
546
Optional<Authentication> auth = SecurityContextUtils.getCurrentAuthentication();
547
548
if (auth.isEmpty()) {
549
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
550
}
551
552
// Get username
553
String username = SecurityContextUtils.getUsername();
554
555
// Check authorities
556
if (SecurityContextUtils.hasRole("USER")) {
557
return ResponseEntity.ok(Map.of("username", username, "role", "user"));
558
} else if (SecurityContextUtils.hasAuthority("ADMIN")) {
559
return ResponseEntity.ok(Map.of("username", username, "role", "admin"));
560
}
561
562
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
563
}
564
565
@PostMapping("/api/admin-action")
566
public ResponseEntity<?> performAdminAction() {
567
// Check multiple roles
568
if (!SecurityContextUtils.hasAnyRole("ADMIN", "SUPER_USER")) {
569
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
570
}
571
572
// Perform admin action
573
String username = SecurityContextUtils.getUsername();
574
log.info("Admin action performed by: {}", username);
575
576
return ResponseEntity.ok("Action completed");
577
}
578
}
579
```
580
581
## Type Converters
582
583
```java { .api }
584
public final class Converters {
585
586
// String converters
587
public static class StringToZonedDateTimeConverter
588
implements Converter<String, ZonedDateTime>;
589
590
public static class StringToLocalDateTimeConverter
591
implements Converter<String, LocalDateTime>;
592
593
// Collection converters
594
public static class StringToCollectionConverter
595
implements Converter<String, Collection>;
596
597
// Custom object converters
598
public static class StringToBeanConverter<T>
599
implements Converter<String, T>;
600
}
601
```
602
603
### Usage Examples
604
605
**Custom converter registration:**
606
```java
607
@Configuration
608
public class ConverterConfiguration {
609
610
@Bean
611
public ConversionService conversionService() {
612
DefaultConversionService service = new DefaultConversionService();
613
614
// Register custom converters
615
service.addConverter(new Converters.StringToZonedDateTimeConverter());
616
service.addConverter(new Converters.StringToLocalDateTimeConverter());
617
service.addConverter(new Converters.StringToCollectionConverter());
618
619
return service;
620
}
621
}
622
```
623
624
This comprehensive Spring integration provides the foundation for building scalable, configurable CAS applications with full Spring Framework support, conditional bean creation, and advanced application context management.