Skip to content

Instantly share code, notes, and snippets.

@agarman
Created June 2, 2022 13:23
Show Gist options
  • Save agarman/14cec9bd4a15d11ce1046bd58946fd71 to your computer and use it in GitHub Desktop.
Save agarman/14cec9bd4a15d11ce1046bd58946fd71 to your computer and use it in GitHub Desktop.
Spring Annotations & Interfaces 101
Spring Annotations & Interfaces 101
@Configuration
- a singleton bean that is used to configure an application
- can be used as a component/bean itself
- can have 0 or more methods that register additional beans
- constructor can take parameters as long as these parameters can be resolved to already registered beans
@Component
- a singleton bean that provides functionality to application
- constructor can take parameters as long as these parameters can be resolved to already registered beans
@Value
- annotation specifying how to set a field using properties or a property loader
- at Manhattan, properties are loaded in this order: component.properties, kv-store, environmental variables
- should use sparringly, preferrably only in @Configuration classes
@Autowired
- annotation specifying that a field should be set from using a registered bean that matches the fields type & name
@Lazy
- annotation specifying to only construct & load a bean when it's referenced
@Bean
- annotation attached to a method to register it's return as a bean
- method can take parameters as long as these parameters can be resolved to already registered beans
@Primary
- annotation attached to a bean to control which instance of a bean to use; resolves an otherwise ambiguous search
ApplicationContextAware
- interface that allows configuration of component after fields are set but before component is registered
- allows loading beans programmatically from ApplicationContext
InitializingBean
- interface that allows configuration of component after fields are set but before component is registered
- prefer InitilizingBean to ApplicationContextAware
Spring Component Lifecycle
1. Construct
2. Set @Value fields
3. Set @Autowired fields
4. Invoke @PostConstruct methods
5. Invoke setApplicationContext from ApplicationContextAware
6. Invoke afterPropertiesSet from InitializingBean
7. Invoke @Bean methods
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment