or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

annotation-configuration.mdapplication-context.mdcaching.mdconfiguration-properties.mddependency-injection.mdevent-handling.mdformatting.mdindex.mdlifecycle-management.mdscheduling.mdvalidation.md

dependency-injection.mddocs/

0

# Dependency Injection

1

2

IoC container functionality providing comprehensive dependency injection capabilities. This includes bean factories, autowiring, qualifier-based injection, JSR-330 support, and various injection patterns for building loosely coupled applications.

3

4

## Capabilities

5

6

### Bean Factory Interfaces

7

8

Core interfaces for the IoC container that manages beans and their dependencies.

9

10

```java { .api }

11

/**

12

* The root interface for accessing a Spring bean container.

13

* This is the basic client view of a bean container.

14

*/

15

public interface BeanFactory {

16

/** Used to dereference a FactoryBean instance and distinguish it from beans created by the FactoryBean */

17

String FACTORY_BEAN_PREFIX = "&";

18

19

/**

20

* Return an instance, which may be shared or independent, of the specified bean.

21

* @param name the name of the bean to retrieve

22

* @return an instance of the bean

23

* @throws NoSuchBeanDefinitionException if there is no bean definition with the specified name

24

* @throws BeansException if the bean could not be obtained

25

*/

26

Object getBean(String name) throws BeansException;

27

28

/**

29

* Return an instance, which may be shared or independent, of the specified bean.

30

* @param name the name of the bean to retrieve

31

* @param requiredType type the bean must match

32

* @return an instance of the bean

33

* @throws NoSuchBeanDefinitionException if there is no bean definition with the specified name

34

* @throws BeanNotOfRequiredTypeException if the bean is not of the required type

35

* @throws BeansException if the bean could not be obtained

36

*/

37

<T> T getBean(String name, Class<T> requiredType) throws BeansException;

38

39

/**

40

* Return the bean instance that uniquely matches the given object type, if any.

41

* @param requiredType type the bean must match

42

* @return an instance of the single bean matching the required type

43

* @throws NoSuchBeanDefinitionException if no bean of the given type was found

44

* @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found

45

* @throws BeansException if the bean could not be obtained

46

*/

47

<T> T getBean(Class<T> requiredType) throws BeansException;

48

49

/**

50

* Return an instance, which may be shared or independent, of the specified bean.

51

* @param name the name of the bean to retrieve

52

* @param args arguments to use when creating a bean instance using explicit arguments

53

* @return an instance of the bean

54

* @throws NoSuchBeanDefinitionException if there is no bean definition with the specified name

55

* @throws BeanDefinitionStoreException if arguments have been given but the affected bean isn't a prototype

56

* @throws BeansException if the bean could not be created

57

*/

58

Object getBean(String name, Object... args) throws BeansException;

59

60

/**

61

* Return an instance, which may be shared or independent, of the specified bean.

62

* @param requiredType type the bean must match

63

* @param args arguments to use when creating a bean instance using explicit arguments

64

* @return an instance of the bean

65

* @throws NoSuchBeanDefinitionException if there is no bean of the given type was found

66

* @throws BeanDefinitionStoreException if arguments have been given but the affected bean isn't a prototype

67

* @throws BeansException if the bean could not be created

68

*/

69

<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;

70

71

/**

72

* Return a provider for the specified bean, allowing for lazy on-demand retrieval of instances.

73

* @param requiredType type the bean must match

74

* @return a corresponding provider handle

75

*/

76

<T> ObjectProvider<T> getBeanProvider(Class<T> requiredType);

77

78

/**

79

* Return a provider for the specified bean, allowing for lazy on-demand retrieval of instances.

80

* @param requiredType type the bean must match (as a ResolvableType)

81

* @return a corresponding provider handle

82

*/

83

<T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType);

84

85

/**

86

* Does this bean factory contain a bean definition or externally registered singleton instance with the given name?

87

* @param name the name of the bean to query

88

* @return whether a bean with the given name is present

89

*/

90

boolean containsBean(String name);

91

92

/**

93

* Is this bean a shared singleton? That is, will getBean(java.lang.String) always return the same instance?

94

* @param name the name of the bean to query

95

* @return whether this bean corresponds to a singleton instance

96

* @throws NoSuchBeanDefinitionException if there is no bean with the given name

97

*/

98

boolean isSingleton(String name) throws NoSuchBeanDefinitionException;

99

100

/**

101

* Is this bean a prototype? That is, will getBean(java.lang.String) always return independent instances?

102

* @param name the name of the bean to query

103

* @return whether this bean will always deliver independent instances

104

* @throws NoSuchBeanDefinitionException if there is no bean with the given name

105

*/

106

boolean isPrototype(String name) throws NoSuchBeanDefinitionException;

107

108

/**

109

* Check whether the bean with the given name matches the specified type.

110

* @param name the name of the bean to query

111

* @param typeToMatch the type to match against (as a ResolvableType)

112

* @return true if the bean type matches, false if it doesn't match or cannot be determined yet

113

* @throws NoSuchBeanDefinitionException if there is no bean with the given name

114

*/

115

boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;

116

117

/**

118

* Check whether the bean with the given name matches the specified type.

119

* @param name the name of the bean to query

120

* @param typeToMatch the type to match against (as a Class)

121

* @return true if the bean type matches, false if it doesn't match or cannot be determined yet

122

* @throws NoSuchBeanDefinitionException if there is no bean with the given name

123

*/

124

boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException;

125

126

/**

127

* Determine the type of the bean with the given name.

128

* @param name the name of the bean to query

129

* @return the type of the bean, or null if not determinable

130

* @throws NoSuchBeanDefinitionException if there is no bean with the given name

131

*/

132

Class<?> getType(String name) throws NoSuchBeanDefinitionException;

133

134

/**

135

* Determine the type of the bean with the given name.

136

* @param name the name of the bean to query

137

* @param allowFactoryBeanInit whether a FactoryBean may get initialized just for the purpose of determining its object type

138

* @return the type of the bean, or null if not determinable

139

* @throws NoSuchBeanDefinitionException if there is no bean with the given name

140

*/

141

Class<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException;

142

143

/**

144

* Return the aliases for the given bean name, if any.

145

* @param name the bean name to check for aliases

146

* @return the aliases, or an empty array if none

147

* @throws NoSuchBeanDefinitionException if there is no bean with the given name

148

*/

149

String[] getAliases(String name) throws NoSuchBeanDefinitionException;

150

}

151

152

/**

153

* Extension of the BeanFactory interface to be implemented by bean factories

154

* that are capable of autowiring and provide bean definitions.

155

*/

156

public interface ListableBeanFactory extends BeanFactory {

157

/**

158

* Check if this bean factory contains a bean definition with the given name.

159

* @param beanName the name of the bean to look for

160

* @return if this bean factory contains a bean definition with the given name

161

*/

162

boolean containsBeanDefinition(String beanName);

163

164

/**

165

* Return the number of beans defined in this factory.

166

* @return the number of beans defined in this factory

167

*/

168

int getBeanDefinitionCount();

169

170

/**

171

* Return the names of all beans defined in this factory.

172

* @return the names of all beans defined in this factory, or an empty array if none defined

173

*/

174

String[] getBeanDefinitionNames();

175

176

/**

177

* Get a provider for the specified bean, allowing for lazy on-demand retrieval of instances.

178

* @param requiredType type the bean must match

179

* @param allowEagerInit whether eager initialization of the underlying bean is allowed

180

* @return a corresponding provider handle

181

*/

182

<T> ObjectProvider<T> getBeanProvider(Class<T> requiredType, boolean allowEagerInit);

183

184

/**

185

* Get a provider for the specified bean, allowing for lazy on-demand retrieval of instances.

186

* @param requiredType type the bean must match (as a ResolvableType)

187

* @param allowEagerInit whether eager initialization of the underlying bean is allowed

188

* @return a corresponding provider handle

189

*/

190

<T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType, boolean allowEagerInit);

191

192

/**

193

* Return the names of beans matching the given type (including subclasses).

194

* @param type the class or interface to match, or null for all bean names

195

* @return the names of beans (or objects created by FactoryBeans) matching the given object type

196

*/

197

String[] getBeanNamesForType(Class<?> type);

198

199

/**

200

* Return the names of beans matching the given type (including subclasses).

201

* @param type the class or interface to match, or null for all bean names

202

* @param includeNonSingletons whether to include prototype or scoped beans too or just singletons

203

* @param allowEagerInit whether to initialize lazy-init singletons and objects created by FactoryBeans

204

* @return the names of beans (or objects created by FactoryBeans) matching the given object type

205

*/

206

String[] getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit);

207

208

/**

209

* Return the bean instances that match the given object type (including subclasses).

210

* @param type the class or interface to match, or null for all concrete beans

211

* @return a Map with the matching beans, containing the bean names as keys and the corresponding bean instances as values

212

* @throws BeansException if a bean could not be created

213

*/

214

<T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException;

215

216

/**

217

* Return the bean instances that match the given object type (including subclasses).

218

* @param type the class or interface to match, or null for all concrete beans

219

* @param includeNonSingletons whether to include prototype or scoped beans too or just singletons

220

* @param allowEagerInit whether to initialize lazy-init singletons and objects created by FactoryBeans

221

* @return a Map with the matching beans, containing the bean names as keys and the corresponding bean instances as values

222

* @throws BeansException if a bean could not be created

223

*/

224

<T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException;

225

226

/**

227

* Find all names of beans which are annotated with the supplied Annotation type.

228

* @param annotationType the type of annotation to look for

229

* @return the names of all matching beans

230

*/

231

String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType);

232

233

/**

234

* Find all beans which are annotated with the supplied Annotation type.

235

* @param annotationType the type of annotation to look for

236

* @return a Map with the matching beans, containing the bean names as keys and the corresponding bean instances as values

237

* @throws BeansException if a bean could not be created

238

*/

239

Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException;

240

241

/**

242

* Find an Annotation of annotationType on the specified bean.

243

* @param beanName the name of the bean to look for annotations on

244

* @param annotationType the type of annotation to look for

245

* @return the annotation of the given type if found, or null otherwise

246

* @throws NoSuchBeanDefinitionException if there is no bean with the given name

247

*/

248

<A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)

249

throws NoSuchBeanDefinitionException;

250

251

/**

252

* Find an Annotation of annotationType on the specified bean.

253

* @param beanName the name of the bean to look for annotations on

254

* @param annotationType the type of annotation to look for

255

* @param allowFactoryBeanInit whether a FactoryBean may get initialized just for the purpose of determining its object type

256

* @return the annotation of the given type if found, or null otherwise

257

* @throws NoSuchBeanDefinitionException if there is no bean with the given name

258

*/

259

<A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType, boolean allowFactoryBeanInit)

260

throws NoSuchBeanDefinitionException;

261

262

/**

263

* Find a Set of Annotations of annotationType on the specified bean.

264

* @param beanName the name of the bean to look for annotations on

265

* @param annotationType the type of annotation to look for

266

* @return a Set of annotations of the given type found, or an empty Set otherwise

267

* @throws NoSuchBeanDefinitionException if there is no bean with the given name

268

*/

269

<A extends Annotation> Set<A> findAllAnnotationsOnBean(String beanName, Class<A> annotationType, boolean allowFactoryBeanInit)

270

throws NoSuchBeanDefinitionException;

271

}

272

273

/**

274

* Extension of the BeanFactory interface to be implemented by bean factories that can autowire.

275

*/

276

public interface AutowireCapableBeanFactory extends BeanFactory {

277

/** Constant that indicates no externally defined autowiring */

278

int AUTOWIRE_NO = 0;

279

280

/** Constant that indicates autowiring bean properties by name */

281

int AUTOWIRE_BY_NAME = 1;

282

283

/** Constant that indicates autowiring bean properties by type */

284

int AUTOWIRE_BY_TYPE = 2;

285

286

/** Constant that indicates autowiring the greediest constructor that can be satisfied */

287

int AUTOWIRE_CONSTRUCTOR = 3;

288

289

/** Constant that indicates determining an appropriate autowire strategy automatically */

290

int AUTOWIRE_AUTODETECT = 4;

291

292

/** Suffix for the "original instance" convention when initializing an existing bean instance */

293

String ORIGINAL_INSTANCE_SUFFIX = ".ORIGINAL";

294

295

/**

296

* Fully create a new bean instance of the given class.

297

* @param beanClass the class of the bean to create

298

* @return the new bean instance

299

* @throws BeansException if instantiation or wiring failed

300

*/

301

<T> T createBean(Class<T> beanClass) throws BeansException;

302

303

/**

304

* Populate the given bean instance through applying after-instantiation callbacks

305

* and bean property post-processing.

306

* @param existingBean the existing bean instance

307

* @throws BeansException if wiring failed

308

*/

309

void autowireBean(Object existingBean) throws BeansException;

310

311

/**

312

* Configure the given raw bean: autowiring bean properties, applying bean property values,

313

* applying factory callbacks such as setBeanName and setBeanFactory, and also applying

314

* all bean post processors.

315

* @param existingBean the existing bean instance

316

* @param beanName the name of the bean

317

* @return the bean instance to use, either the original or a wrapped one

318

* @throws BeansException if the initialization failed

319

*/

320

Object configureBean(Object existingBean, String beanName) throws BeansException;

321

322

/**

323

* Fully create a new bean instance of the given class with the specified autowire strategy.

324

* @param beanClass the class of the bean to create

325

* @param autowireMode by name or type, using the constants in this interface

326

* @param dependencyCheck whether to perform a dependency check for objects

327

* @return the new bean instance

328

* @throws BeansException if instantiation or wiring failed

329

*/

330

Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;

331

332

/**

333

* Instantiate a new bean instance of the given class with the specified autowire strategy.

334

* @param beanClass the class of the bean to instantiate

335

* @param autowireMode by name or type, using the constants in this interface

336

* @param dependencyCheck whether to perform a dependency check for object references in the bean instance

337

* @return the new bean instance

338

* @throws BeansException if instantiation or wiring failed

339

*/

340

Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;

341

342

/**

343

* Autowire the bean properties of the given bean instance by name or type.

344

* @param existingBean the existing bean instance

345

* @param autowireMode by name or type, using the constants in this interface

346

* @param dependencyCheck whether to perform a dependency check for object references in the bean instance

347

* @throws BeansException if wiring failed

348

*/

349

void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck) throws BeansException;

350

351

/**

352

* Apply the property values of the bean definition with the given name to the given bean instance.

353

* @param existingBean the existing bean instance

354

* @param beanName the name of the bean definition in the bean factory

355

* @throws BeansException if applying the property values failed

356

*/

357

void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException;

358

359

/**

360

* Initialize the given raw bean, applying factory callbacks such as setBeanName and setBeanFactory,

361

* also applying all bean post processors.

362

* @param existingBean the existing bean instance

363

* @param beanName the name of the bean

364

* @return the bean instance to use, either the original or a wrapped one; may be null

365

* @throws BeansException if the initialization failed

366

*/

367

Object initializeBean(Object existingBean, String beanName) throws BeansException;

368

369

/**

370

* Apply BeanPostProcessors to the given existing bean instance.

371

* @param existingBean the existing bean instance

372

* @param beanName the name of the bean

373

* @return the bean instance to use, either the original or a wrapped one; may be null

374

* @throws BeansException if any post-processing failed

375

*/

376

Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException;

377

378

/**

379

* Apply BeanPostProcessors to the given existing bean instance.

380

* @param existingBean the existing bean instance

381

* @param beanName the name of the bean

382

* @return the bean instance to use, either the original or a wrapped one; may be null

383

* @throws BeansException if any post-processing failed

384

*/

385

Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException;

386

387

/**

388

* Destroy the given bean instance (typically coming from createBean(java.lang.Class<T>)),

389

* applying the DisposableBean contract as well as registered DestructionAwareBeanPostProcessors.

390

* @param existingBean the bean instance to destroy

391

*/

392

void destroyBean(Object existingBean);

393

394

/**

395

* Resolve the bean instance that uniquely matches the given object type, if any.

396

* @param requiredType type the bean must match

397

* @return an instance of the single bean matching the required type

398

* @throws BeansException if the bean could not be created

399

*/

400

<T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType) throws BeansException;

401

402

/**

403

* Resolve a bean instance for the given bean name, providing a dependency descriptor for exposure to target factory methods.

404

* @param name the name of the bean to look up

405

* @param descriptor the dependency descriptor for the requesting injection point

406

* @return the corresponding bean instance

407

* @throws BeansException if the bean could not be created

408

*/

409

Object resolveBeanByName(String name, DependencyDescriptor descriptor) throws BeansException;

410

411

/**

412

* Resolve the specified dependency against the beans defined in this factory.

413

* @param descriptor the descriptor for the dependency (field/method/constructor)

414

* @param requestingBeanName the name of the bean which declares the given dependency

415

* @return the resolved object, or null if not found

416

* @throws BeansException if dependency resolution failed

417

*/

418

Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName) throws BeansException;

419

420

/**

421

* Resolve the specified dependency against the beans defined in this factory.

422

* @param descriptor the descriptor for the dependency (field/method/constructor)

423

* @param requestingBeanName the name of the bean which declares the given dependency

424

* @param autowiredBeanNames a Set that all names of autowired beans should be added to

425

* @param typeConverter the TypeConverter to use for populating arrays and collections

426

* @return the resolved object, or null if not found

427

* @throws BeansException if dependency resolution failed

428

*/

429

Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName,

430

Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException;

431

}

432

```

433

434

### Autowiring Annotations

435

436

Annotations for declarative dependency injection and qualification.

437

438

```java { .api }

439

/**

440

* Marks a constructor, field, setter method, or config method as to be autowired by Spring's dependency injection facilities.

441

*/

442

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})

443

@Retention(RetentionPolicy.RUNTIME)

444

public @interface Autowired {

445

/**

446

* Declares whether the annotated dependency is required.

447

* @return whether the annotated dependency is required

448

*/

449

boolean required() default true;

450

}

451

452

/**

453

* This annotation may be used on a field or parameter as a qualifier for candidate beans when autowiring.

454

*/

455

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})

456

@Retention(RetentionPolicy.RUNTIME)

457

@Qualifier

458

public @interface Qualifier {

459

/**

460

* The qualifying value for the annotation.

461

* @return the qualifier value

462

*/

463

String value() default "";

464

}

465

466

/**

467

* Marks a field or method as being autowired by Spring's dependency injection facilities.

468

*/

469

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})

470

@Retention(RetentionPolicy.RUNTIME)

471

public @interface Value {

472

/**

473

* The actual value expression such as "#{systemProperties.myProp}" or property placeholder such as "${my.app.myProp}".

474

* @return the value expression

475

*/

476

String value();

477

}

478

```

479

480

### JSR-330 Support

481

482

JSR-330 (javax.inject) standard annotations support for dependency injection.

483

484

```java { .api }

485

/**

486

* Identifies injectable constructors, methods, and fields.

487

* May apply to static as well as instance members.

488

*/

489

@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})

490

@Retention(RetentionPolicy.RUNTIME)

491

public @interface Inject {

492

}

493

494

/**

495

* Identifies a type that the injector only instantiates once.

496

*/

497

@Target({ElementType.TYPE, ElementType.METHOD})

498

@Retention(RetentionPolicy.RUNTIME)

499

public @interface Singleton {

500

}

501

502

/**

503

* Identifies qualifier annotations.

504

*/

505

@Target(ElementType.ANNOTATION_TYPE)

506

@Retention(RetentionPolicy.RUNTIME)

507

public @interface Qualifier {

508

}

509

510

/**

511

* String-based qualifier.

512

*/

513

@Qualifier

514

@Retention(RetentionPolicy.RUNTIME)

515

public @interface Named {

516

/**

517

* The name.

518

* @return the name

519

*/

520

String value() default "";

521

}

522

523

/**

524

* Provides instances of T. Typically implemented by an injector.

525

*/

526

public interface Provider<T> {

527

/**

528

* Provides an instance of T.

529

* @return an instance of T

530

*/

531

T get();

532

}

533

```

534

535

### ObjectProvider Interface

536

537

Enhanced provider interface for accessing beans with additional features.

538

539

```java { .api }

540

/**

541

* A variant of ObjectFactory designed specifically for injection points,

542

* allowing for programmatic optionality and lenient not-unique handling.

543

*/

544

public interface ObjectProvider<T> extends ObjectFactory<T>, Iterable<T> {

545

/**

546

* Return an instance (possibly shared or independent) of the object managed by this factory.

547

* @return an instance of the bean

548

* @throws BeansException in case of creation errors

549

*/

550

T getObject() throws BeansException;

551

552

/**

553

* Return an instance (possibly shared or independent) of the object managed by this factory.

554

* @param args arguments to use when creating a corresponding instance

555

* @return an instance of the bean

556

* @throws BeansException in case of creation errors

557

*/

558

T getObject(Object... args) throws BeansException;

559

560

/**

561

* Return an instance (possibly shared or independent) of the object managed by this factory.

562

* @return an instance of the bean, or null if not available

563

*/

564

T getIfAvailable() throws BeansException;

565

566

/**

567

* Return an instance (possibly shared or independent) of the object managed by this factory.

568

* @param supplier a callback for supplying a default object if none is present in the factory

569

* @return an instance of the bean, or the supplied default object if no such bean is available

570

*/

571

T getIfAvailable(Supplier<T> supplier) throws BeansException;

572

573

/**

574

* Consume an instance (possibly shared or independent) of the object managed by this factory, if available.

575

* @param consumer a callback for processing the target object if available

576

* @throws BeansException in case of creation errors

577

*/

578

void ifAvailable(Consumer<T> consumer) throws BeansException;

579

580

/**

581

* Return an instance (possibly shared or independent) of the object managed by this factory.

582

* @return an instance of the bean

583

* @throws BeansException in case of creation errors or if not exactly one bean found

584

*/

585

T getIfUnique() throws BeansException;

586

587

/**

588

* Return an instance (possibly shared or independent) of the object managed by this factory.

589

* @param supplier a callback for supplying a default object if no unique candidate is present in the factory

590

* @return an instance of the bean, or the supplied default object if no such bean is available or if it is not unique

591

*/

592

T getIfUnique(Supplier<T> supplier) throws BeansException;

593

594

/**

595

* Consume an instance (possibly shared or independent) of the object managed by this factory, if unique.

596

* @param consumer a callback for processing the target object if unique

597

* @throws BeansException in case of creation errors

598

*/

599

void ifUnique(Consumer<T> consumer) throws BeansException;

600

601

/**

602

* Return an Iterator over all matching object instances, without specific ordering guarantees.

603

* @return an Iterator over all matching object instances

604

*/

605

Iterator<T> iterator();

606

607

/**

608

* Return a sequential Stream over all matching object instances, without specific ordering guarantees.

609

* @return a sequential Stream over all matching object instances

610

*/

611

Stream<T> stream();

612

613

/**

614

* Return a sequential Stream over all matching object instances, without specific ordering guarantees.

615

* @return a sequential Stream over all matching object instances

616

*/

617

Stream<T> orderedStream();

618

}

619

```

620

621

### Bean Definition Support

622

623

Interfaces and classes for programmatic bean definition and registration.

624

625

```java { .api }

626

/**

627

* Interface for holding a bean definition with name and aliases.

628

*/

629

public interface BeanDefinitionHolder {

630

/**

631

* Return the wrapped BeanDefinition.

632

* @return the wrapped BeanDefinition

633

*/

634

BeanDefinition getBeanDefinition();

635

636

/**

637

* Return the primary name of the bean, as specified for the bean definition.

638

* @return the primary name of the bean

639

*/

640

String getBeanName();

641

642

/**

643

* Return the alias names for the bean, as specified directly for the bean definition.

644

* @return the alias names, or null if none

645

*/

646

String[] getAliases();

647

}

648

649

/**

650

* A BeanDefinition describes a bean instance, which has property values,

651

* constructor argument values, and further information supplied by concrete implementations.

652

*/

653

public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement {

654

/** Scope identifier for the standard singleton scope */

655

String SCOPE_SINGLETON = ConfigurableBeanFactory.SCOPE_SINGLETON;

656

657

/** Scope identifier for the standard prototype scope */

658

String SCOPE_PROTOTYPE = ConfigurableBeanFactory.SCOPE_PROTOTYPE;

659

660

/** Role hint indicating that a BeanDefinition is a major part of the application */

661

int ROLE_APPLICATION = 0;

662

663

/** Role hint indicating that a BeanDefinition is a supporting part of some larger configuration */

664

int ROLE_SUPPORT = 1;

665

666

/** Role hint indicating that a BeanDefinition is providing an entirely background role */

667

int ROLE_INFRASTRUCTURE = 2;

668

669

/**

670

* Set the name of the parent definition of this bean definition, if any.

671

* @param parentName the name of the parent definition

672

*/

673

void setParentName(String parentName);

674

675

/**

676

* Return the name of the parent definition of this bean definition, if any.

677

* @return the parent name, or null if none

678

*/

679

String getParentName();

680

681

/**

682

* Specify the bean class name of this bean definition.

683

* @param beanClassName the bean class name

684

*/

685

void setBeanClassName(String beanClassName);

686

687

/**

688

* Return the current bean class name of this bean definition.

689

* @return the bean class name, or null if none defined

690

*/

691

String getBeanClassName();

692

693

/**

694

* Override the target scope of this bean, specifying a new scope name.

695

* @param scope the new scope name

696

*/

697

void setScope(String scope);

698

699

/**

700

* Return the name of the current target scope for this bean, or null if not known yet.

701

* @return the scope name, or null

702

*/

703

String getScope();

704

705

/**

706

* Set whether this bean should be lazily initialized.

707

* @param lazyInit whether to apply lazy initialization

708

*/

709

void setLazyInit(boolean lazyInit);

710

711

/**

712

* Return whether this bean should be lazily initialized.

713

* @return whether to apply lazy initialization

714

*/

715

boolean isLazyInit();

716

717

/**

718

* Set the names of the beans that this bean depends on being initialized.

719

* @param dependsOn the names of beans that this bean depends on

720

*/

721

void setDependsOn(String... dependsOn);

722

723

/**

724

* Return the bean names that this bean depends on.

725

* @return the names of beans that this bean depends on, or null if none

726

*/

727

String[] getDependsOn();

728

729

/**

730

* Set whether this bean is a candidate for getting autowired into some other bean.

731

* @param autowireCandidate whether this bean is a candidate for autowiring

732

*/

733

void setAutowireCandidate(boolean autowireCandidate);

734

735

/**

736

* Return whether this bean is a candidate for getting autowired into some other bean.

737

* @return whether this bean is a candidate for autowiring

738

*/

739

boolean isAutowireCandidate();

740

741

/**

742

* Set whether this bean is a primary autowire candidate.

743

* @param primary whether this bean is a primary autowire candidate

744

*/

745

void setPrimary(boolean primary);

746

747

/**

748

* Return whether this bean is a primary autowire candidate.

749

* @return whether this bean is a primary autowire candidate

750

*/

751

boolean isPrimary();

752

753

/**

754

* Specify the factory bean to use, if any.

755

* @param factoryBeanName the name of the factory bean

756

*/

757

void setFactoryBeanName(String factoryBeanName);

758

759

/**

760

* Return the factory bean name, if any.

761

* @return the factory bean name, or null if none

762

*/

763

String getFactoryBeanName();

764

765

/**

766

* Specify a factory method, if any.

767

* @param factoryMethodName the name of the factory method

768

*/

769

void setFactoryMethodName(String factoryMethodName);

770

771

/**

772

* Return a factory method, if any.

773

* @return the factory method name, or null if none

774

*/

775

String getFactoryMethodName();

776

777

/**

778

* Return the constructor argument values for this bean.

779

* @return the ConstructorArgumentValues (never null)

780

*/

781

ConstructorArgumentValues getConstructorArgumentValues();

782

783

/**

784

* Return if there are constructor argument values defined for this bean.

785

* @return if there are constructor argument values defined for this bean

786

*/

787

default boolean hasConstructorArgumentValues() {

788

return !getConstructorArgumentValues().isEmpty();

789

}

790

791

/**

792

* Return the property values to be applied to a new instance of the bean.

793

* @return the MutablePropertyValues (never null)

794

*/

795

MutablePropertyValues getPropertyValues();

796

797

/**

798

* Return if there are property values defined for this bean.

799

* @return if there are property values defined for this bean

800

*/

801

default boolean hasPropertyValues() {

802

return !getPropertyValues().isEmpty();

803

}

804

805

/**

806

* Set the name of the initializer method.

807

* @param initMethodName the name of the initializer method

808

*/

809

void setInitMethodName(String initMethodName);

810

811

/**

812

* Return the name of the initializer method.

813

* @return the name of the initializer method, or null if none

814

*/

815

String getInitMethodName();

816

817

/**

818

* Set the name of the destroy method.

819

* @param destroyMethodName the name of the destroy method

820

*/

821

void setDestroyMethodName(String destroyMethodName);

822

823

/**

824

* Return the name of the destroy method.

825

* @return the name of the destroy method, or null if none

826

*/

827

String getDestroyMethodName();

828

829

/**

830

* Set the role hint for this BeanDefinition.

831

* @param role the role hint

832

*/

833

void setRole(int role);

834

835

/**

836

* Get the role hint for this BeanDefinition.

837

* @return the role hint

838

*/

839

int getRole();

840

841

/**

842

* Set a human-readable description of this bean definition.

843

* @param description the description

844

*/

845

void setDescription(String description);

846

847

/**

848

* Return a human-readable description of this bean definition.

849

* @return the description, or null if none

850

*/

851

String getDescription();

852

853

/**

854

* Return a resolvable type for this bean definition, based on the bean class or other specific metadata.

855

* @return a resolvable type (never null)

856

*/

857

ResolvableType getResolvableType();

858

859

/**

860

* Return whether this a Singleton, with a single, shared instance returned on all calls.

861

* @return whether this is a singleton

862

*/

863

boolean isSingleton();

864

865

/**

866

* Return whether this a Prototype, with an independent instance returned for each call.

867

* @return whether this is a prototype

868

*/

869

boolean isPrototype();

870

871

/**

872

* Return whether this bean is "abstract", that is, not meant to be instantiated.

873

* @return whether this bean is abstract

874

*/

875

boolean isAbstract();

876

}

877

```

878

879

### Usage Examples

880

881

**Basic Autowiring:**

882

883

```java

884

import org.springframework.beans.factory.annotation.Autowired;

885

import org.springframework.stereotype.Service;

886

import org.springframework.stereotype.Repository;

887

888

@Service

889

public class UserService {

890

891

private final UserRepository userRepository;

892

893

// Constructor injection (recommended)

894

@Autowired

895

public UserService(UserRepository userRepository) {

896

this.userRepository = userRepository;

897

}

898

899

public User findUser(Long id) {

900

return userRepository.findById(id);

901

}

902

}

903

904

@Repository

905

public class UserRepository {

906

public User findById(Long id) {

907

// Implementation

908

return null;

909

}

910

}

911

```

912

913

**Field and Setter Injection:**

914

915

```java

916

@Service

917

public class OrderService {

918

919

// Field injection

920

@Autowired

921

private PaymentService paymentService;

922

923

// Setter injection with optional dependency

924

private NotificationService notificationService;

925

926

@Autowired(required = false)

927

public void setNotificationService(NotificationService notificationService) {

928

this.notificationService = notificationService;

929

}

930

}

931

```

932

933

**Qualifier-based Injection:**

934

935

```java

936

@Service

937

public class PaymentService {

938

939

@Autowired

940

@Qualifier("creditCardProcessor")

941

private PaymentProcessor creditCardProcessor;

942

943

@Autowired

944

@Qualifier("paypalProcessor")

945

private PaymentProcessor paypalProcessor;

946

}

947

948

@Component

949

@Qualifier("creditCardProcessor")

950

public class CreditCardProcessor implements PaymentProcessor {

951

}

952

953

@Component

954

@Qualifier("paypalProcessor")

955

public class PayPalProcessor implements PaymentProcessor {

956

}

957

```

958

959

**Using ObjectProvider:**

960

961

```java

962

@Service

963

public class NotificationService {

964

965

private final ObjectProvider<EmailSender> emailSenderProvider;

966

private final ObjectProvider<SmsSender> smsSenderProvider;

967

968

@Autowired

969

public NotificationService(ObjectProvider<EmailSender> emailSenderProvider,

970

ObjectProvider<SmsSender> smsSenderProvider) {

971

this.emailSenderProvider = emailSenderProvider;

972

this.smsSenderProvider = smsSenderProvider;

973

}

974

975

public void sendNotification(String message) {

976

// Optional dependency - send email if available

977

emailSenderProvider.ifAvailable(sender -> sender.send(message));

978

979

// Get SMS sender or use default

980

SmsSender smsSender = smsSenderProvider.getIfAvailable(DefaultSmsSender::new);

981

smsSender.send(message);

982

983

// Process all available implementations

984

emailSenderProvider.stream().forEach(sender -> sender.send(message));

985

}

986

}

987

```

988

989

**Value Injection:**

990

991

```java

992

@Component

993

public class DatabaseConfig {

994

995

@Value("${database.url}")

996

private String databaseUrl;

997

998

@Value("${database.timeout:30}")

999

private int timeout;

1000

1001

@Value("#{systemProperties['user.home']}")

1002

private String userHome;

1003

1004

@Value("${database.pools}")

1005

private List<String> poolNames;

1006

1007

public DataSource createDataSource() {

1008

// Use injected values to configure DataSource

1009

return null;

1010

}

1011

}

1012

```

1013

1014

**JSR-330 Support:**

1015

1016

```java

1017

import javax.inject.Inject;

1018

import javax.inject.Named;

1019

import javax.inject.Singleton;

1020

1021

@Singleton

1022

@Named("userServiceImpl")

1023

public class UserServiceImpl implements UserService {

1024

1025

private final UserRepository repository;

1026

1027

@Inject

1028

public UserServiceImpl(@Named("primaryRepository") UserRepository repository) {

1029

this.repository = repository;

1030

}

1031

}

1032

```