3 annotation bean scope, java code config

8 Spring Configuration with Java Annotations - Bean Scopes and Lifecycle Methods

8.1 Bean Scopes

@Component
@Scope("Singleton")//default
public class TennisCoach implements Coach{
...
}

//@Scope("prototype")

8.2 Bean Lifecycle Methods - Annotations

Development Process

  1. Define your methods for init and destroy

  2. Add annotations: @PostConstruct and @PreDestroy

@PostConstruct: Code will execute after constructor and after injection of dependencies

@PreDestroy: Code will execute before bean is destroyed

e.g.

//define my init method
    @PostConstruct
    public void doStartupStuff() {
        System.out.println(">> TennisCoach init!");
    }

Note: For "prototype" scoped beans, Spring does not call the @PreDestroy method. Gasp!

In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance.

Thus, although initialization lifecycle callback methods are called on all objects regardless of scope,in the case of prototypes, configured destruction lifecycle callbacks are not called. The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding.

To get the Spring container to release resources held by prototype-scoped beans, try using a custombean post-processor, which holds a reference to beans that need to be cleaned up.

9. Spring Configuration with Java Code

  • Instead of configuring Spring container using XML

  • Configure the Spring container with Java cod

  • 3 ways of configuring Spring Container

  • Full XML config

  • XML Component Scan

  • Java Configuration Class

e.g. 1

<bean id = "myCoach" class ="com.springdemo.TrackCoach">
<constructor-arg ref = "myFortuneService" />
</bean>

e.g.2

<context:component-scan base-package="com.springdemo" />

e.g.3

@Configuration
@ComponentScan("com.springdemo")//package to scan
public class SportConfig{
}

9.1 Development Process

  1. Create a Java class and annotate as @Configuration

  2. Add component scanning support:@ComponentScan(optional)

  3. Read Spring Java configuration class

  4. Retrieve bean from Spring container

e.g.3

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SportConfig.class);

9.2 Defining Beans in Spring

Development Process:

  1. Define method to expose bean

  2. Inject bean dependencies

  3. Read Spring Java configuration class

  4. Retrieve bean from Spring container

9.3 Injecting Values from Properties File

Development Process

  1. Create Properties File

  2. Load Properties File in Spring config

  3. Reference values from Properties File

e.g.2

@Configuration
@PropertySource("classpath:sport.properties")
public class SportConfig{
 ...
}

Last updated