Spring Framework
Bean Management
Annotationsmust be used onpublicmethods defined ininterfacesto ensure that theproxycan be created.
Bean Factory
Application Event
- Additional Capabilities of the ApplicationContext :: Spring Framework - Standard and Custom Events (opens in a new tab)
- ApplicationEvent (Spring Framework 6.1.3 API) (opens in a new tab)
FactoryBean
org.springframework.beans.factory.FactoryBean
-
Used to create bean instances, example:
LocalSessionFactoryBean -
The
FactoryBeanclassimplementsFactoryBeaninterface and implements 2 methods:getObject(): returns the bean instancegetObjectType(): returns the type of the bean instance
-
The
FactoryBeanclass is declared as a Spring bean in theApplicationContextconfiguration file. -
Inject the bean that is created by the
FactoryBeanclass, not theFactoryBeanclass itself. -
Pros
- The advantage of using
FactoryBeanis that you don't need to change how the beans are injected, only how they are created.
- The advantage of using
-
Cons
FactoryBeancan be used to createprototypebeans, but need to call explicitlyapplicationContext.getBean()to trigger the creation of a new bean instance.
-
Alternative
- Use
Supplierto create a new instance of a bean.
- Use
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
thisis not a proxy, so@Cacheablewill 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.processScheduledTaskto examine how tasks are scheduled -
Use
/actuator/scheduledtasksto view scheduled tasks -
The
cronexpression inSpringscheduler is comprised ofsix 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
@EnableAsyncto the@SpringBootApplicationclass or a@Configurationclass - Can only be used on
publicmethods with avoidor ajava.util.concurrent.Futurereturn type.