Spring Chinese Translation

Spring IoC container

1.1 introduction to IOC container and Bean

Inversion of Control (IoC) is also called Dependency Injection (DI). This is a process in which multiple objects define their dependencies (call relationships between objects) only by setting properties after constructor parameters, factory method parameters, or object instances are initialized by the constructor or created and returned by the factory method. The container injects dependencies between after it creates beans. This process and the bean itself control the instantiation or location of its dependencies by using the direct constructor of the class or the service location mechanism. It is basically the opposite (so it is called control inversion).

The new object is created artificially, and the instance and calling relationship of the object are controlled by itself, which is transformed into container control. The control side changes, so it is control reversal

org.springframework.beans and org.springframework.context are the foundation of the Spring IoC container
BeanFactory interface provides a high-level configuration mechanism for managing objects of any type
ApplicationContext is a sub interface of BeanFactory. supplement

  • Easier integration with Spring's AOP features
  • Information resource processing (for internationalization)
  • Event release
  • Application layer specific context. (for example, the use of WebApplicationContext in Web Applications)

In short, BeanFactory provides a configuration framework and basic functions. ApplicationContext adds more enterprise specific functions. ApplicationContext is a complete superset of BeanFactory.

In Spring, Beans, which constitute the backbone of an application and are managed by the Spring IoC container, are called Beans. A bean is an object instantiated, assembled and managed by the Spring IoC container. Otherwise, a bean is just one of many objects in your application. The dependencies between Beans are reflected by the configuration elements used by the container.

1.2 vessel overview

The org.springframework.context.ApplicationContext interface represents the Spring IOC container and is responsible for instantiating, configuring and assembling beans. The container obtains how to instantiate, configure and assemble by reading the configuration elements. Configuration metadata is represented by XML document, java annotation and java code. It allows you to represent the rich dependencies between the objects that make up the application.

Spring provides the implementation of multiple ApplicationContext interfaces. In independent applications, you usually create an instance of ClasPathXmolApplicationContext or FileSystemXmlApplicationContext. Although XML has always been the traditional format for defining configuration metadata, you can declaratively enable support for these additional metadata formats by providing a small number of XML configurations, instructing the container to use Java comments or code as the metadata format.

In most application scenarios, there is no need for explicit user code to instantiate one or more Spring IoC container instances (implemented through xml file configuration).

The following figure shows a high-level view of how Spring works. Your application class is combined with configuration metadata, so after ApplicationContext is created and initialized, you have a fully configured and executable system or application.

1.2.1 configuration metadata

As shown in the figure above, the Spring IoC container uses a form of configuration metadata. This configuration metadata represents how you, as an application developer, tell the Spring container to instantiate, configure, and assemble objects in your application.

Configuration metadata is traditionally provided in a simple and intuitive XML format.

  • XML configuration
  • Annotation based configuration
  • Java based configuration

A Spring configuration contains at least one and usually more than one bean definition that the container must manage.
XML based configuration metadata configures these beans in < beans / > < beans / >.
Java Configuration usually uses the @ Bean annotation method in the @ Configuration class

These bean definitions correspond to the actual objects that make up the application. Generally, you define service layer objects, data access objects (DAOs), persistent objects (Struts Action instances), infrastructure objects (Hibernate SessionFactories, JMS Queues, etc.). Typically, fine-grained domain objects are no longer configured in the container, because creating and loading domain objects is usually the responsibility of DAO and business logic. However, you can use the integration of Spring and AspectJ to configure the created objects outside the control of the IoC container

Basic format of XML configuration element data

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Should id Property is a string that identifies a single bean definition
    	Should class Attribute definition bean Type of,And use the fully qualified class name. -->
    <bean id="..." class="...">  
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->

</beans>

1.2.2 instantiate a container

One or more location paths provided to the ApplicationContext constructor are resource strings, which allow the container to load configuration metadata from various external resources (such as local file system, JavaCLASSPATH, etc.).

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

Service layer object (services.xml) configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- services -->

    <bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
        <property name="accountDao" ref="accountDao"/>
        <property name="itemDao" ref="itemDao"/>
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>
    
    <!-- more bean definitions for services go here -->

</beans>

Data access layer object (DAO), (daos.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="accountDao"
        class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao">
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions for data access objects go here -->

</beans>

In the previous example, the service layer consists of the PetStoreServiceImpl class and two data access objects: JpaAccountDao and JpaItemDao (based on the JPA object relational mapping standard). The property name element refers to the name of the JavaBean property, and the ref element refers to the name of another bean definition. This relationship between id and ref elements expresses the dependencies between collaboration objects.

Write xml based configuration metadata

It is useful to have bean definitions span multiple XML files. Typically, each individual XML configuration file represents a logical layer or module in your schema.

You can use the application context constructor to load bean definitions from all of these XML fragments. The constructor takes multiple Resource locations. Alternatively, use one or more < import / > elements to load the bean definition from another file or files

<beans>
    <import resource="services.xml"/>
    <import resource="resources/messageSource.xml"/>
    <import resource="/resources/themeSource.xml"/>

    <bean id="bean1" class="..."/>
    <bean id="bean2" class="..."/>
</beans>

In the above example, the external bean definition is loaded from three files: services. XML, MessageSource. XML, and themesource. XML. All location paths are relative to the definition file that executes the import, so services.xml must be located in the same directory or classpath location as the file that executes the import, and messageSource.xml and themeSource.xml must be located under the location of the resources import file. As you can see, a leading slash is ignored. However, since these paths are relative, it is best not to use slashes at all. According to the Spring Schema, the contents of the imported file, including the top-level < beans / > elements, must be valid XML bean definitions.

1.2.3 use of containers

ApplicationContext is a high-level factory interface that can maintain dependencies between different beans and. By using t getBean (string name, class < T > requiredtype), you can obtain an instance of the bean

ApplicationContext lets you read bean definitions and access them

// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);

// use configured instance
List<String> userList = service.getUsernameList();

The most flexible variant is the GenericApplicationContext combined with the delegate of the reader -- for example, combined with the xmlbeandefinitionreader for XML file, as shown in the following example:

GenericApplicationContext context = new GenericApplicationContext();
new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml", "daos.xml");
context.refresh();

Delegates of such readers can be mixed and matched on the same ApplicationContext to read bean definitions from different configuration sources.

You can use getBean to get bean instances, and the ApplicationContext interface has other methods to retrieve beans, but ideally, your application code should never use them. In fact, your application code should not call the getBean() method at all, so it is completely independent of the Spring API. For example, Spring's integration with the Web framework provides dependency injection for various Web framework components (such as controllers and JSF managed beans), allowing you to declare dependencies on specific beans through metadata (such as auto assembly annotations).

1.3 Bean overview

The Spring IoC container manages one or more beans. These beans are created based on the configuration metadata you provide to the container (for example, in the form of XML < bean / > definition).

Within the container itself, these bean definitions are represented as BeanDefinition objects, which contain (among other information) the following metadata:

  • A package qualifies the class name: usually the actual implementation class of the defined bean.
  • Bean behavior configuration element, which describes the behavior of the bean in the container (scope, lifecycle callback, etc.)
  • References to other beans that the bean needs to perform its work. These references are also called collaborators or dependencies.
  • Other configuration settings set in the newly created object -- for example, the number of connections used in the bean that manages the connection pool or the size limit of the connection pool.
Property explain
Class Actual implementation class of Bean
Name Naming of beans
Scope Bean scope
Constructor arguments
Properties
Autowiring mode
Lazy initialization mode
Initialization method
Destruction

In addition to containing information about how to create a specific bean, the ApplicationContext implementation allows the registration of existing objects created outside the container (by the user). This is done by accessing the BeanFactory of ApplicationContext and returning the implementation of BeanFactory DefaultListableBeanFactory by using the getBeanFactory() method. DefaultListableBeanFactory supports this registration through the registerSingleton(..) and registerBeanDefinition(..) methods. However, a typical application uses only beans defined through regular bean definition metadata.

1.3.1 Beans naming

Each bean has one or more identifiers. These identifiers must be unique in the container that manages the bean. A bean usually has only one identifier. However, if it requires more than one, you can treat the extra as an alias.

In XML based configuration metadata, you can use the id attribute, the name attribute, or both to specify the bean identifier. The id attribute allows you to specify an id. Typically, these names are alphanumeric ('myBean ',' someService ', etc.), but they can also contain special characters. If you want to introduce other aliases for beans, you can also specify them in the name attribute, separated by commas (,), semicolons (;), or spaces.

You do not need to provide a name or an id for the bean. If you do not explicitly provide a name or id, the container generates a unique name for the bean. However, if you want to reference the bean by name, you must provide a name by using the ref element or the service locator style. The motivation for not providing names is related to the use of internal beans and auto assembly collaborators

Alias the Bean outside the Bean definition

In the bean definition itself, you can provide multiple names for a bean by using a combination of up to one name specified by the id attribute and any number of other names in the name attribute. These names can be equivalent aliases for the same bean and are useful in some cases, such as having each component in the application reference a public dependency by using the component's own specific bean name.

However, it is not always sufficient to specify all aliases where beans are defined. Sometimes you need to introduce aliases for beans defined elsewhere. This is common in large systems, where the configuration is split between each subsystem, and each subsystem has its own set of object definitions. In the XML based configuration metadata, you can use the < alias / > element to complete this operation

<alias name="fromName" alias="toName"/>

In this case, the named bean (in the same container) fromName can also be called toName after using this alias definition

For example, the configuration metadata of subsystem A may refer to A data source named subsystema DataSource. The configuration metadata of subsystem B may refer to A data source named subsystemb DataSource. When the main application combines the two subsystems, the main application references the DataSource through myapp DataSource. To have all three names refer to the same object, you can add the following alias definitions to the configuration metadata:

<alias name="myApp-dataSource" alias="subsystemA-dataSource"/><alias name="myApp-dataSource" alias="subsystemB-dataSource"/>

1.3.2 Beans instantiation

A bean definition is essentially a method for creating one or more objects. When asked, the container looks at the method of the named bean and uses the configuration metadata encapsulated by the bean definition to create (or get) the actual object.

If you use XML based configuration metadata, specify the type (or class) of the object to be instantiated in the class attribute of the < bean / > element. This class attribute (internally, it is a class attribute of the BeanDefinition instance) is usually mandatory. You can use this attribute in one of two ways:

  • Generally, when the container itself directly creates beans by calling its constructor through reflection, specifying the bean class to be constructed is a bit equivalent to Java code with new operator
  • Call the specified actual class (the factory method containing static) to create the object. In less common cases, the container calls the static factory method on the class to create the bean. The object type returned by calling the static factory method may be the same class or completely another class.

Initialize with constructor

When you create beans through constructor methods, all common classes can be used and compatible with Spring. That is, the class being developed does not need to implement any specific interface or code in a specific way. Simply specifying the bean class is sufficient. However, depending on the IoC type you use for that particular bean, you may need a default (empty) constructor.

The Spring IoC container can manage almost any class you want it to manage. Most Spring users prefer the actual JavaBeans. It has only a default (parameterless) constructor and appropriate setter s and getter s (modeled on the properties in the container).

<bean id="exampleBean" class="examples.ExampleBean"/><bean name="anotherExample" class="examples.ExampleBeanTwo"/>

Instantiate using static factory methods

When defining a bean created using a static factory method, use the class attribute to specify the class containing the static factory method and a property named factory method (specify the name of the factory method itself). You should be able to call this method (with optional parameters, as described below) and return a living object that is then treated as created by the constructor. One use of this bean definition is to invoke the static factory in legacy code.

The following bean definition specifies that a bean is created by calling a factory method. The type (class) of the return object is not specified in the definition, only the class containing the factory method is specified. In this example, the createInstance() method must be static. The following example shows how to specify a factory method:

<bean id="clientService"    class="examples.ClientService"    factory-method="createInstance"/>
public class ClientService {    private static ClientService clientService = new ClientService();    private ClientService() {}    public static ClientService createInstance() {        return clientService;    }}

Instantiate using the instance factory method

Similar to the instantiation of static factory methods, instantiate the non static method of calling an existing bean from the container using the instance factory method to create a new bean. To use this mechanism, leave the class attribute blank and specify the name of the bean in the current (or parent or ancestor) container in the factory bean attribute, which contains the instance method to call to create the object. Use the factory method property to set the name of the factory method itself.

<!-- the factory bean, which contains a method called createInstance() --><bean id="serviceLocator" class="examples.DefaultServiceLocator">    <!-- inject any dependencies required by this locator bean --></bean><!-- the bean to be created via the factory bean --><bean id="clientService"    factory-bean="serviceLocator"    factory-method="createClientServiceInstance"/>
public class DefaultServiceLocator {    private static ClientService clientService = new ClientServiceImpl();    public ClientService createClientServiceInstance() {        return clientService;    }}

A factory class can also contain multiple factory methods

<bean id="serviceLocator" class="examples.DefaultServiceLocator">    <!-- inject any dependencies required by this locator bean --></bean><bean id="clientService"    factory-bean="serviceLocator"    factory-method="createClientServiceInstance"/><bean id="accountService"    factory-bean="serviceLocator"    factory-method="createAccountServiceInstance"/>
public class DefaultServiceLocator {    private static ClientService clientService = new ClientServiceImpl();    private static AccountService accountService = new AccountServiceImpl();    public ClientService createClientServiceInstance() {        return clientService;    }    public AccountService createAccountServiceInstance() {        return accountService;    }}

Determines the runtime type of the Bean

Determining the runtime type of a particular bean is not easy. The specified class in the bean metadata definition is only an initial class reference, which may be combined with the declared factory method, or the FactoryBean class may lead to different runtime types of the bean, or the root is not set when the instance factory method (resolved by specifying the factory bean name). In addition, AOP proxies may wrap bean instances with interface based proxies and limit exposure to the actual type of the target bean (only the interface it implements).

The recommended way to find out the actual runtime type of a particular bean is the bean name specified by the BeanFactory.getType call. This takes all of the above into account and returns the object type that the BeanFactory.getBean call will return for the same bean name.

1.4 dependencies

A typical enterprise application does not contain a single object. Even the simplest application has multiple objects that work together to present a coherent application as seen by the end user.

1.4.1 dependency injection

Dependency injection (DI) is a process in which objects define their dependencies (call relationships between objects) only by setting properties after being initialized by the constructor, factory method parameters, or object instances are created and returned by the factory method. The container injects dependencies between after it creates beans. This process and the bean itself control the instantiation or location of its dependencies by using the direct constructor of the class or the service location mechanism. It is basically the opposite (so it is called control inversion).

There are two main variants of DI: constructor based dependency injection and Setter based dependency injection

Constructor based dependency injection

Constructor based DI is accomplished by calling a constructor with multiple parameters, each representing a dependency. Calling static factory methods with specific parameters to construct bean s is almost equivalent.

Classes that can only use constructors for dependency injection

public class SimpleMovieLister {    // the SimpleMovieLister has a dependency on a MovieFinder    private final MovieFinder movieFinder;    // a constructor so that the Spring container can inject a MovieFinder    public SimpleMovieLister(MovieFinder movieFinder) {        this.movieFinder = movieFinder;    }    // business logic that actually uses the injected MovieFinder is omitted...}

Constructor parameter parsing

The constructor performs parameter resolution matching by using the type of the parameter. Then the order in which constructor parameters are defined in the bean definition is the order in which these parameters are provided to the appropriate constructor when instantiating the bean.

package x.y;public class ThingOne {    public ThingOne(ThingTwo thingTwo, ThingThree thingThree) {        // ...    }}
<beans>    <bean id="beanOne" class="x.y.ThingOne">        <constructor-arg ref="beanTwo"/>        <constructor-arg ref="beanThree"/>    </bean>    <bean id="beanTwo" class="x.y.ThingTwo"/>    <bean id="beanThree" class="x.y.ThingThree"/></beans>

When using basic types

package examples;public class ExampleBean {    // Number of years to calculate the Ultimate Answer    private final int years;    // The Answer to Life, the Universe, and Everything    private final String ultimateAnswer;    public ExampleBean(int years, String ultimateAnswer) {        this.years = years;        this.ultimateAnswer = ultimateAnswer;    }}

Constructor parameter type match

The type of constructor parameter is explicitly specified via the type attribute

<bean id="exampleBean" class="examples.ExampleBean">    <constructor-arg type="int" value="7500000"/>    <constructor-arg type="java.lang.String" value="42"/></bean>

Constructor parameter index

Use the index property to explicitly specify the index of the constructor parameter (the index starts at 0)

<bean id="exampleBean" class="examples.ExampleBean">    <constructor-arg index="0" value="7500000"/>    <constructor-arg index="1" value="42"/></bean>

Constructor parameter name

You can disambiguate values using constructor parameter names

<bean id="exampleBean" class="examples.ExampleBean">    <constructor-arg name="years" value="7500000"/>    <constructor-arg name="ultimateAnswer" value="42"/></bean>

Dependency injection based on Setter

DI based on Setter is accomplished by invoking a parameterless constructor or a parameterless static factory method to instantiate bean and then invoke the setter method on bean.

public class SimpleMovieLister {    // the SimpleMovieLister has a dependency on the MovieFinder    private MovieFinder movieFinder;    // a setter method so that the Spring container can inject a MovieFinder    public void setMovieFinder(MovieFinder movieFinder) {        this.movieFinder = movieFinder;    }    // business logic that actually uses the injected MovieFinder is omitted...}
Because you can mix constructor based and constructor based setter of DIļ¼ŒTherefore, as a rule of thumb, use constructors for mandatory dependencies and constructors for optional dependencies setter Method or configuration method is a good rule of thumb. Spring Teams often advocate constructor injection because it allows you to implement application components as immutable objects and ensure that the required dependencies are not null. 

Dependency resolution process

The bean dependency resolution executed by the container is as follows:

  • ApplicationContext is created and initialized according to all beans described in the configuration metadata.
  • The dependencies of each bean are expressed in the form of properties, constructor parameters, or parameters of a static factory method if you use it instead of a normal constructor. These dependencies are provided to the bean when the bean is actually created.
  • Each property or constructor parameter is the actual definition of the value to be set, or a reference to another bean in the container
  • Each property or constructor parameter of a value is converted from its specified format to the actual type of the property or constructor parameter. By default, Spring can convert the value provided in String format to all built-in types, such as int, long, String, boolean, etc.

The Spring container validates the configuration of each bean when creating the container. However, the bean property itself is not set before the bean is actually created. When a container is created, a singleton scope is created and set as a pre instantiated (default) bean.. The scope is defined in Bean Scopes. Otherwise, the bean is created only when requested. Creating a bean may lead to the creation of a bean graph because bean dependencies and their dependencies (and so on) are created and allocated. Note that resolution mismatches between these dependencies may occur later - that is, when the affected bean is first created.

Circular dependency if you mainly use constructor injection, you may create a circular dependency scenario that cannot be solved. For example: A Class needs to be injected through the constructor B Class, B Class needs to be injected through the constructor A Class. If you add a class A and B of bean Configured for mutual injection, then Spring IoC The container detects this circular reference at run time and throws a BeanCurrentlyInCreationException.One possible solution is to edit the source code of some classes so that setter Instead of constructors. Alternatively, avoid constructor injection and use only setter Injection. In other words, although not recommended, it can be passed setter Injection to configure cyclic dependencies. Unlike the typical case (no cyclic dependency), bean A and bean B The circular dependency between forces one of them bean Inject another before full initialization bean(Classic chicken and egg scene).

You can usually trust spring to do the right thing. It detects configuration problems when the container loads, such as references to non-existent beans and circular dependencies. Spring sets properties and resolves dependencies as late as possible when actually creating beans. This means that if there is a problem creating the object or its dependencies, the properly loaded spring container can later generate an exception when you request the object -- for example, the bean will throw an exception because it is missing or invalid. This potential latency visibility of some configuration problems is why ApplicationContext implements pre instantiated singleton beans by default. At the expense of some upfront time and memory, create these beans before they are actually needed. You will find configuration problems when creating ApplicationContext, not later. You can still override this default behavior so that the singleton bean delays initialization instead of eagerly pre instantiating.

If there is no circular dependency, when one or more collaboration beans are injected into dependent beans, each collaboration bean has been fully configured before injecting dependent beans. This means that if bean A depends on bean B, the Spring IoC container fully configures bean B before calling the setter method on bean A. In other words, the bean is instantiated (if it is not a pre instantiated singleton), its dependencies are set, and related lifecycle methods (such as the configured init method or InitializingBean callback method) are called.

Examples of dependency resolution

setter based DI

<bean id="exampleBean" class="examples.ExampleBean">    <!-- setter injection using the nested ref element -->    <property name="beanOne">        <ref bean="anotherExampleBean"/>    </property>    <!-- setter injection using the neater ref attribute -->    <property name="beanTwo" ref="yetAnotherBean"/>    <property name="integerProperty" value="1"/></bean><bean id="anotherExampleBean" class="examples.AnotherBean"/><bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
public class ExampleBean {    private AnotherBean beanOne;    private YetAnotherBean beanTwo;    private int i;    public void setBeanOne(AnotherBean beanOne) {        this.beanOne = beanOne;    }    public void setBeanTwo(YetAnotherBean beanTwo) {        this.beanTwo = beanTwo;    }    public void setIntegerProperty(int i) {        this.i = i;    }}

Constructor based DI

<bean id="exampleBean" class="examples.ExampleBean">    <!-- constructor injection using the nested ref element -->    <constructor-arg>        <ref bean="anotherExampleBean"/>    </constructor-arg>    <!-- constructor injection using the neater ref attribute -->    <constructor-arg ref="yetAnotherBean"/>    <constructor-arg type="int" value="1"/></bean><bean id="anotherExampleBean" class="examples.AnotherBean"/><bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
public class ExampleBean {    private AnotherBean beanOne;    private YetAnotherBean beanTwo;    private int i;    public ExampleBean(        AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {        this.beanOne = anotherBean;        this.beanTwo = yetAnotherBean;        this.i = i;    }}

Instead of using the constructor, use a static factory method

<bean id="exampleBean" class="examples.ExampleBean" factory-method="createInstance">    <constructor-arg ref="anotherExampleBean"/>    <constructor-arg ref="yetAnotherBean"/>    <constructor-arg value="1"/></bean><bean id="anotherExampleBean" class="examples.AnotherBean"/><bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
public class ExampleBean {    // a private constructor    private ExampleBean(...) {        ...    }    // a static factory method; the arguments to this method can be    // considered the dependencies of the bean that is returned,    // regardless of how those arguments are actually used.    public static ExampleBean createInstance (        AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {        ExampleBean eb = new ExampleBean (...);        // some other operations...        return eb;    }}

Example factory method

// Only modify factory bean < bean id = "examplebean" factory bean = "examples. Examplebean" factory method = "createinstance" > < constructor Arg ref = "otherexamplebean" / > < constructor Arg ref = "yetanotherbean" / > < constructor Arg value = "1" / > < / bean > < bean id = "otherexamplebean" class = "examples. Anotherbean" / > < bean id = "yetanotherbean" class= "examples.YetAnotherBean"/>
public class ExampleBean {    // a private constructor    private ExampleBean(...) {        ...    }    public ExampleBean createInstance (        AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {        ExampleBean eb = new ExampleBean (...);        // some other operations...        return eb;    }}

Keywords: Spring

Added by juminoz on Tue, 23 Nov 2021 18:39:30 +0200