bean管理(xml配置方式)
1-在spring裏面通過配置文件創建對象
2-bean實例化三種方式實現
使用類的無參構造(重點)實際開發中常用
package lcn.spring.ioc;
public class User {
//注意xml配置文件會自動找類中的無參構造
//:如果有有參數的構造函數,還需要定義個無參的構造,不然會報錯
public void add(){
System.out.println("add.....");
}
}
使用靜態工廠創建在類的裏面創建靜態的方法,返回類的對象
package lcn.spring.bean;
public class Bean2 {
public void add(){
System.out.println("Bean2>>>>>>>>>>>>>");
}
}
package lcn.spring.bean;
public class Bean2Factory {
//使用工廠類間接的創建Bean2對象
public static Bean2 getBean2(){
return new Bean2();
}
}
使用實例工廠創建創建不是靜態的方法(用類對象創建),返回類的對象
package lcn.spring.bean;
public class Bean3 {
public void add(){
System.out.println("BEAN3***********");
}
}
package lcn.spring.bean;
public class Bean3Factory {
//創建一個普通的方法,返回bean3對象
public Bean3 getBean3(){
return new Bean3();
}
}
spring配置文件applicationcontent.xml<?xml version="1.0" encoding="UTF-8"?>
<!-- schema約束 -->
<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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- ioc入門
配置對象的創建 -->
<bean id="user" class="lcn.spring.ioc.User"></bean>
<!-- 使用靜態工廠類創建返回對象,缺點繁瑣 ,一般很少使用-->
<bean id="bean2" class="lcn.spring.bean.Bean2Factory" factory-method="getBean2"></bean>
<!-- 使用實例工廠創建對象 -->
<!-- 創建工廠對象 -->
<bean id="bean3Factory" class="lcn.spring.bean.Bean3Factory"></bean>
<bean id="bean3" factory-bean="bean3Factory" factory-method="getBean3"></bean>
</beans>
juint測試:package lcn.spring.ioc;
import lcn.spring.bean.Bean2;
import lcn.spring.bean.Bean3;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestIoc {
@Test
public void testUser(){
//加載spring配置文件,根據配置創建對象
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
//得到配置的創建的對象
User user = (User) context.getBean("user");
System.out.println("user="+user);
user.add();
}
@Test
public void testBean2Factory(){
//加載spring配置文件,根據配置創建對象
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
//得到配置的創建的對象
Bean2 bean2 = (Bean2) context.getBean("bean2");
System.out.println("bean2="+bean2);
bean2.add();
}
@Test
public void testBean3Factory(){
//加載spring配置文件,根據配置創建對象
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
//得到配置的創建的對象
Bean3 bean3 = (Bean3) context.getBean("bean3");
System.out.println("bean3="+bean3);
bean3.add();
}
}