spring基礎應用(2)——依賴注入
阿新 • • 發佈:2022-01-05
依賴注入
當spring中一個物件A需要依賴另一個物件B的時候,我們需要在A裡面引入一個B,同時需要給B注入一個物件,在這裡我們先說的是手動裝配,跟後面的自動裝配autowired暫時沒有關係。
通常手動裝配一個物件我們有兩種方法:
- 構造方法注入
- set方法注入
接下來我們依次來看,先看構造方法注入
構造方法注入
示例1:constructor-arg裡面是ref
public class BeanOne {
public BeanOne(BeanTwo beanTwo){
}
}
<?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="beanOne" class="com.ali.testspring.BeanOne"> <constructor-arg ref="beanTwo"></constructor-arg> <!-- inject any dependencies required by this locator bean --> </bean> <bean id="beanTwo" class="com.ali.testspring.BeanTwo"> <!-- inject any dependencies required by this locator bean --> </bean> </beans>
示例2:
當需要給基本資料型別和字串注入的時候
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; } }
//可以用type和value <bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg type="int" value="7500000"/> <constructor-arg type="java.lang.String" value="42"/> </bean> //可以用index和value <bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg index="0" value="7500000"/> <constructor-arg index="1" value="42"/> </bean> //也可以用name和value <bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg name="years" value="7500000"/> <constructor-arg name="ultimateAnswer" value="42"/> </bean>