Spring Framework
Bean Management
Annotations
must be used onpublic
methods defined ininterfaces
to ensure that theproxy
can 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
FactoryBean
classimplements
FactoryBean
interface and implements 2 methods:getObject()
: returns the bean instancegetObjectType()
: returns the type of the bean instance
-
The
FactoryBean
class is declared as a Spring bean in theApplicationContext
configuration file. -
Inject the bean that is created by the
FactoryBean
class, not theFactoryBean
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.
- The advantage of using
-
Cons
FactoryBean
can be used to createprototype
beans, but need to call explicitlyapplicationContext.getBean()
to trigger the creation of a new bean instance.
-
Alternative
- Use
Supplier
to 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
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 inSpring
scheduler 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
@EnableAsync
to the@SpringBootApplication
class or a@Configuration
class - Can only be used on
public
methods with avoid
or ajava.util.concurrent.Future
return type.