In most cases, beanfactory directly uses the New Keyword to call the constructor to create a bean instance. The class attribute specifies the implementation class of the bean instance. However, this is not the only way to instantiate a bean.
There are three methods to create a bean::
① Call the constructor to create a bean instance.
② Call the static factory method to create the bean.
③ Call the instance factory method to create a bean.
This article discusses how to create a bean instance using the constructor:
Using constructors to create bean instances is the most common case. If you use the set injection method, this class is required to provide a non-parameter constructor.
Beanfactory uses the non-parameter constructor to create a bean instance. This instance is a default instance, and spring performs default Initialization on all attributes of the bean instance, that is, values of all basic types are initialized to 0 or false, and values of all reference types are initialized to null.
Next, beanfactory decides the dependency according to the configuration file. It first instantiates the dependent bean instance and then injects the dependency for the bean. Finally, return a complete bean instance to the program. All attributes of the bean instance have been initialized by the spring container.
Axe. Java:
public interface Axe {public String chop();}
Person. Java:
public interface Person {public void useAxe();}
Steelaxe. Java:
Public class steelaxe implements axe {@ overridepublic string chop () {return "cutting firewood really fast";} public steelaxe () {system. out. println ("Spring instantiation dependent Bean: steelaxe instance... ");}}
Chinese. Java:
Public class Chinese implements person {@ overridepublic void useaxe () {system. out. println (axe. chop ();} private axe; Public void setaxe (axe) {This. AXE = axe;} Public Chinese () {system. out. println ("Spring instantiation of the main Bean: Chinese instance... ");}}
Bean. XML Core Configuration:
<bean id="chinese" class="com.bean.Chinese"> <property name="axe" ref="steelAxe"/> </bean> <bean id="steelAxe" class="com.bean.SteelAxe"/>
Test. Java:
public class Test {public static void main(String[] args) {ApplicationContext ctx=new ClassPathXmlApplicationContext("bean.xml");Person person=(Person) ctx.getBean("chinese");person.useAxe();}}
Run test. Java and the console outputs:
The execution results clearly reflectExecution Process:
① The program creates an applicationcontext instance.
② Call the default constructor of the Chinese class to create a default instance.
③ Inject dependency according to the configuration file: instantiate the dependent Bean first, and then inject the dependent bean.
④ Return a complete Chinese instance.