Bean實例化的方式
1.在spring裏面通過配置文件創建對象
2.bean實例化三種方式實現
第一種 使用類的無參數構造創建(重點)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<bean id="user" class="cn.itcast.ioc.User"></bean>
</beans>
注意:類裏面沒有無參的構造會出現異常
第二種 使用靜態工廠創建
(1)創建靜態的方法,返回類對象
public class Bean2Factory {
//靜態的方法,返回Bean2對象
public static Bean2 getBean2() {
return new Bean2();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 使用靜態工廠創建對象 -->
<bean id="bean2" class="cn.itcast.bean.Bean2Factory" factory-method="getBean2">
</bean>
</beans>
第三種 使用實例工廠創建
(1)創建不是靜態的方法,返回類對象
public class Bean3Factory {
//普通的方法,返回Bean3對象
public Bean3 getBean3() {
return new Bean3();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 使用靜態工廠創建對象 -->
<!-- 創建工廠對象 -->
<bean id="bean3Factory" class="cn.itcast.bean.Bean3Factory"></bean>
<bean id="bean3" factory-bean="bean3Factory" factory-method="getBean3"></bean>
</beans>