Spring Framework notes

Spring Framework

Bean Management

  • Annotations must be used on public methods defined in interfaces to ensure that the proxy can be created.

Bean Factory

Application Event

FactoryBean

org.springframework.beans.factory.FactoryBean

  • Used to create bean instances, example: LocalSessionFactoryBean

  • The FactoryBean class implements FactoryBean interface and implements 2 methods:

    • getObject(): returns the bean instance
    • getObjectType(): returns the type of the bean instance
  • The FactoryBean class is declared as a Spring bean in the ApplicationContext configuration file.

  • Inject the bean that is created by the FactoryBean class, not the FactoryBean class itself.

  • Pros

    • The advantage of using FactoryBean is that you don't need to change how the beans are injected, only how they are created.
  • Cons

    • FactoryBean can be used to create prototype beans, but need to call explicitly applicationContext.getBean() to trigger the creation of a new bean instance.
  • Alternative

    • Use Supplier to create a new instance of a bean.

PropertySource

Manipulating property sources

Property sources may be removed, reordered, or replaced; and additional property sources may be added using the MutablePropertySources instance returned from getPropertySources(). The following examples are against the StandardEnvironment implementation of ConfigurableEnvironment, but are generally applicable to any implementation, though particular default property sources may differ.

Reference: ConfigurableEnvironment

Exmaple - Adding a new property source with highest search priority
ConfigurableEnvironment environment = new StandardEnvironment();
MutablePropertySources propertySources = environment.getPropertySources();
Map<String, Object> myMap = new HashMap<>();
myMap. put("xyz", "myValue");
propertySources.addFirst(new MapPropertySource("MY_MAP", myMap));
Exmaple - Removing the default system properties property source
MutablePropertySources propertySources = environment.getPropertySources();
propertySources.remove(StandardEnvironment. SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)
Exmaple - Mocking the system environment for testing purposes
MutablePropertySources propertySources = environment.getPropertySources();
MockPropertySource mockEnvVars = new MockPropertySource().withProperty("xyz", "myValue");
propertySources.replace(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, mockEnvVars);

Spring Expression

  • System property:
@Value("#{systemProperties['priority']}")
// or
@Value("${priority}")
  • Default value:
@Value("#{systemProperties['unknown'] ?: 'some default'}")
// or
@Value("${unknown.param:some default}")
  • Precedence: System properties > User defined properties (.properties file)
  • Literals
    • direct input as string
    • can be automatically converted, exceptions thrown upon conversion error
@Value("8080")
int port;

Data Access

Transaction Management

Query

Entity Graph
Query By Example

Caching

Cache Abstraction

  • @Cacheable
Invoke Cacheable method within the same class
  • this is not a proxy, so @Cacheable will not work

Scheduling

TaskExecutor

  • Customize the TaskExecutor

    @Bean
    TaskExecutor taskExecutor() {
      var threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
      threadPoolTaskExecutor.setThreadNamePrefix("Async-");
      threadPoolTaskExecutor.setCorePoolSize(2);
      threadPoolTaskExecutor.setMaxPoolSize(6);
      threadPoolTaskExecutor.setQueueCapacity(5);
      return threadPoolTaskExecutor;
    }

@Scheduled

  • Check ScheduledAnnotationBeanPostProcessor.processScheduledTask to examine how tasks are scheduled

  • Use /actuator/scheduledtasks to view scheduled tasks

  • The cron expression in Spring scheduler is comprised of six fields.

    ┌───────────── second (0-59)
    │ ┌───────────── minute (0 - 59)
    │ │ ┌───────────── hour (0 - 23)
    │ │ │ ┌───────────── day of the month (1 - 31)
    │ │ │ │ ┌───────────── month (1 - 12) (or JAN-DEC)
    │ │ │ │ │ ┌───────────── day of the week (0 - 7)
    │ │ │ │ │ │          (or MON-SUN -- 0 or 7 is Sunday)
    │ │ │ │ │ │
    * * * * * *

@Async

  • Add @EnableAsync to the @SpringBootApplication class or a @Configuration class
  • Can only be used on public methods with a void or a java.util.concurrent.Future return type.