spring的bean管理(xml方式)
作者:互联网
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>
标签:xml,静态,spring,bean,实例,Bean3,Bean2,创建,public 来源: https://blog.csdn.net/GUYIIT/article/details/99692353