Spring Flashcards
What is a Spring Bean?
a Spring bean is an object which Spring framework manages at runtime. It is the basic building block of any Spring application.
What is involved in Spring managing a Spring Bean?
Creating an object,
Providing dependencies (e.g. other beans, configuration properties)
Intercepting object method calls to provide additional framework features
Destroying an object
How does Spring know what beans to create?
Spring has to create beans, you provide the recipe in BEAN DEFINITIONS (which classes to use as beans)
How do you define a Spring Bean?
1 - @Component on the class (usu. if you have access to the source code)
2 - @Bean in a custom config class (if you don’t own the code)
3 - declare a bean in an XML config file (not common anymore)
What are 3 common derivatives of @Component?
@Service
@Controller
@Repository
These are all @Component, but with info about what jobs they do
You don’t want your class to be dependent on Spring, but you still want Spring to create a bean. What do you do?
Use @Bean in a custom config class.
What is @Configuration?
Also @Component, but it marks the class as the holder of bean definitions
What are Spring Bean properties?
Properties give details about HOW Spring should create objects. Spring creates default properties, but you can customize.
Name some Spring Bean properties.
class name dependencies scope initialization mode initialization callback destruction callback
Explain Bean class.
When you define a bean, you connect to a single concrete class in your application. The class is the main property of the bean.
Explain Bean name
A custom string that Spring uses to identify beans. Unlike Bean class, bean names are unique across the application. (Spring makes up its own names at runtime by default, so this is optional) WHY? Mostly for when you have several beans for the same class defined with @Bean. (still pretty rare)
Define 2 beans of the same class type
@Configuration class MyConfigurationClass {
@Bean(name = "myBeanClass") MyBeanClass myBeanClass() { return new MyBeanClass(); }
@Bean(name = "anotherMyBeanClass") MyBeanClass anotherMyBeanClass() { return new MyBeanClass(); } }
Explain Bean dependencies
Sometimes beans need other beans to do their jobs. Spring needs to create them in the right order (dependencies first), but you don’t have to worry about it as long as you specify the dependencies.
How do you define Bean dependencies?
If you have a class marked @Component and there is a constructor with parameters, Spring will use the parameters as dependencies.
@Autowired on the constructor. When is it not necessary?
When there is only one constructor in the class marked with @Component. If you have multiple constructors, you need to mark one with @Autowired so Spring can find the right dependencies.