Spring Learning (2) --- Assembling Beans in the IoC Container

A Spring configuration overview 1. Spring
container high-level view
  To successfully start the Spring container in the application, the following three conditions need to be met:
  • The thunderstorms of the Spring framework have been placed in the classpath of the application;
  • The application provides Spring with complete Bean configuration information;
  • Bean classes are already placed on the application's classpath.




2. XML-based configuration



2. Dependency injection

1. Attribute injection
<bean id="car" class="com.baobaobao.ditype.Car">
  <property name="maxSpeed"><value>200</value></property>
  <property name="brand"><value>奔驰</value></property>
  <property name="price"><value>2000000</value></property>
</bean>

Each property of a bean corresponds to a <property> tag, which is the name of the property, and has a corresponding Setter method in the Bean implementation class. Spring will only check whether there is a corresponding Setter method in the bean. As for whether there is a corresponding attribute variable in the bean, there is no requirement.
Note : JavaBean's special attribute naming convention, under normal circumstances, java attribute variable names start with lowercase letters. However, attribute variable names starting with uppercase letters are also allowed, but must meet the requirement of "the first two letters of the variable are either all uppercase or all lowercase".

2. Constructor injection
<bean id="car" class="com.baobaobao.ditype.Car">
  <constructor-arg index="0" type="java.lang.String">
     <value>奔驰</value>
  </constructor-arg>
  <constructor-arg index="1" type="double">
     <value>20000</value>
   </constructor-arg>
</bean>


Since a class can have multiple constructors, there are several ways to match input parameters.

3. Factory Method Injection

<!--Non-static factory method: Need to create a factory instance-->
<bean id="carFactory" class="com.baobaobao.ditype.CarFactory"/>
<!-- factory-bean specifies the factory class Bean above; factory-method specifies the factory method for the factory class to create the bean-->
<bean id="car5" factory-bean="carFactory" factory-method="createHongQiCar"/>

<!--Static Factory Method-->
<bean id="carFactory" class="com.baobaobao.ditype.CarFactory" factory-method="createHongQiCar/>


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326991936&siteId=291194637