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();
}
}