introduction
In the Spring framework, the creation of beans is usually done directly by the container through the reflection mechanism. However, in some scenarios, the creation logic of objects is more complicated (for example, it requires dependence on external resources, dynamic proxy or customized initialization process), and then it is directly passed@Bean
Annotations may not meet the requirements.FactoryBean
It is a powerful interface provided by Spring, allowing developers toProgrammatically control the creation process of beans
。
1. What is FactoryBean?
FactoryBean
is an interface in the Spring framework (locatedpackage), used to create complex objects. Unlike a normal bean, it is itself a "factory" responsible for generating an instance of another bean.
Core Methods
public interface FactoryBean<T> { T getObject() throws Exception; // Return the actual object Class<?> getObjectType(); // Return object type boolean isSingleton(); // Is it a single case}
The difference between FactoryBean and ordinary beans
-
Ordinary Bean
: Containers are instantiated directly and manage their life cycle -
FactoryBean
: The container will call itgetObject()
Method returns the target object- When defining a name
myFactoryBean
FactoryBean,("myFactoryBean")
The return isgetObject()
Results - If you need to obtain FactoryBean itself, you need to use it
("&myFactoryBean")
(Previously added to the name&
)
- When defining a name
2. Typical usage scenarios of FactoryBean
- Integrated third-party library
- For example, MyBatis'
SqlSessionFactoryBean
, used to create complexSqlSessionFactory
Object
- For example, MyBatis'
- Delay initialization and complex logic
- When the creation of an object requires reading configuration, connecting to a database, or computing parameters, the logic can be encapsulated through FactoryBean
- Dynamic proxy generation object
- For example, in Spring AOP
ProxyFactoryBean
, used to generate proxy objects
- For example, in Spring AOP
- Unified management of resources
- For example, create client objects that need to connect to external services (such as Redis, HTTP clients)
3. Practical cases: Custom FactoryBean
Suppose we need to create different brands of
Car
Object, the following are the implementation steps
1. Define the target object
public class Car { private String brand; private int maxSpeed; // Omit the construction method, Getter/Setter}
2. Implement FactoryBean interface
public class CarFactoryBean implements FactoryBean<Car> { private String brand; private int maxSpeed; // Inject configuration values through attributes public void setBrand(String brand) { = brand; } public void setMaxSpeed(int maxSpeed) { = maxSpeed; } @Override public Car getObject() throws Exception { // Complex initialization logic (example here only) return new Car(brand, maxSpeed); } @Override public Class<?> getObjectType() { return ; } @Override public boolean isSingleton() { return true; // Singleton mode } }
3. Annotation configuration method
@Configuration public class AppConfig { @Bean public CarFactoryBean teslaCar() { CarFactoryBean factory = new CarFactoryBean(); ("Tesla"); (250); return factory; } }
4. Get Bean
ApplicationContext context = ...; Car car = ("teslaCar", ); // What is obtained is a Car objectFactoryBean<?> factory = ("&teslaCar", ); // Get FactoryBean itself
4. Things to note
- Distinguish FactoryBean from Target Bean
- use
&
Prefix to get FactoryBean instance itself
- use
- Avoid repeated creation
- like
isSingleton()
returntrue
,make suregetObject()
Method returns the same instance each time
- like
- Compatibility with @Primary/@Qualifier
- The annotation acts on the target object generated by the FactoryBean, not the FactoryBean itself
Summarize
FactoryBean
It is a high-level customization mechanism in Spring, suitable forCreation scenarios of complex objects
. Through it, developers can flexibly control the initialization process of beans and achieve seamless integration with third-party libraries. After understanding its design principles, you can significantly improve your understanding of the internal working mechanism of Spring containers.
This is the article about in-depth understanding of Spring FactoryBean: A secret weapon for flexibly creating complex objects. For more related Spring FactoryBean content to create complex objects, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!