spring——IOC容器使用
阿新 • • 發佈:2020-07-27
-
建立相關的類(這裡是直接在之前類的基礎上進行修改)
package com.guan.dao; public interface Fruit { String getFruit(); }
package com.guan.dao; public class FruitImpl implements Fruit { public String getFruit() { return "Buy Some fruit"; } }
package com.guan.service; import com.guan.dao.Fruit; public interface UserService { String buyFruit(); void setFruit(Fruit fruit); }
package com.guan.service; import com.guan.dao.Apple; import com.guan.dao.Fruit; import com.guan.dao.FruitImpl; public class UserServiceImpl implements UserService{ Fruit fruit; public UserServiceImpl() { fruit = new FruitImpl(); } public String buyFruit() { return fruit.getFruit(); } public void setFruit(Fruit fruit){ this.fruit = fruit; } }
-
在resources目錄下新增配置檔案:beans.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="fruit" class="com.guan.dao.FruitImpl"></bean> <bean id="apple" class="com.guan.dao.Apple"></bean> <bean id="userService" class="com.guan.service.UserServiceImpl"> <property name="fruit" ref="fruit"></property> </bean> </beans>
注:
(1).即便沒有屬性需要初始化也需要通過
<bean>
來對其進行例項化,而不再需要new(2).
<property>
的注入需要類中存在set方法(3).對於屬性的賦值的兩種方式
- 對於基本型別的賦值可以用value屬性
- 對於物件型別可以用ref(reference)屬性以及
<bean>
中的id初始化
-
建立並使用例項
import com.guan.dao.Fruit; import com.guan.service.UserService; import com.guan.service.UserServiceImpl; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { public static void main(String[] args) { //create and configure beans ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); //retrieve configured instance UserService userService = (UserService) context.getBean("userService"); System.out.println(userService.buyFruit()); } }
-
其它相關配置
-
alias:給bean起別名,可以用多個不同的別名取出同一個類的例項
-
bean
(1).id:bean的唯一識別符號
(2).class:bean物件所應的全限定名(包名+類名)
(3).name:也是別名,可以取同時取多個別名
-
import:用於團隊開發使用,可以將多個配置檔案匯入合併為一個.那麼在呼叫時只要匯入一個配置檔案即可