Spring 3:创建Bean

=======================================================

※ 创建Bean实例的方式

 1) 通过构造器(有参或无参)
      方式: <bean id="" class=""/>

之前用的都是这种方式,不在详细说明。

 2) 通过静态工厂方法
  方式: <bean id/name="目标对象" class="工厂类" factory-method="静态工厂方法"/>
注意:工厂类不会被实例化
利用静态factory方法创建,可以统一管理各个bean的创建,如各个bean在创建之前需要相同
的初始化处理,则可用这个factory方法险进行统一的处理等等。
     

例子:  
    public class HelloBeanFactory {   
        public static HelloBean createHelloBean() {   
            return new HelloBean();   
           }   
    }
    
    xml:配置
    //构造器配置
     ﹤bean id="sayhello" class="test.service.impl.HelloBean"/﹥        
//静态工厂
      ﹤bean id="sayhello2" class="test.service.impl.HelloBeanFactory" factory-method="createHelloBean"/﹥  
例:

工厂类

package com.briup.bean;

import java.io.InputStream;
import java.util.Properties;

/*
 * 工厂:类中有一个方法专门产生某一类对象
 * DL
 */
public class staticFactory {
	private static Properties pro=null;
	
	public static Properties getPro() {
		return pro;
	}

	public static void setPro(Properties pro) {
		staticFactory.pro = pro;
	}
	/*
	 * 静态工厂
	 * 特点:staticFactory.getSer();
	 * 无法注入参数
	 */
	public static UserService getSer() {
		//return new UserService(),new的还是指定对象
		//一般工厂要求将路径写在xml文件或properties文件
		//retuen new UserService();
		UserService us=null;
		try {
			if(pro==null) {
			synchronized (staticFactory.class) {
			if(pro==null) {
				pro=new Properties();
			//pro.load(new FileReader("src/com/briup/IOC/us.properties"));
			//相对当前位置读取文件
				InputStream is=
			staticFactory.class.getResourceAsStream("../IOC/us.properties");
				pro.load(is);
			    }
			  }
			}
				us=(UserService) Class.forName(pro.getProperty("service")).newInstance();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return us;
	}
}

us.properties文件

service=com.briup.bean.UserService
dao=com.briup.bean.UserDao


配置文件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
          http://www.springframework.org/schema/beans/spring-beans.xsd">
 <!--factory-method和class属性
     spring不构建对象,直接类名.方法名()调用该方法
     返回值赋给name属性  -->
 <bean name="us" class="com.briup.bean.staticFactory" factory-method="getSer">
 </bean>
 </beans>



测试代码:

@Test
	public void staticF_test() {
			//System.out.println(staticFactory.getSer());
			ClassPathXmlApplicationContext cp=
					new ClassPathXmlApplicationContext("com/briup/IOC/staticFactory.xml");
	          System.out.println(cp.getBean("us"));		      
	}


3)通过实例工厂方法(非静态方法)
  方式:
    <bean id="factory" class="工厂类"/>
<bean id="" factory-bean="factory" factory-method="实例工厂方法"/>
利用实例化factory方法创建,即将factory方法也作为了业务bean来控制

工厂Java文件:
public class HelloBeanInstanceFactory {   
public Hello createHelloBean() {   
return new HelloBean();   
}
xml:
﹤bean id="factory" class="test.service.impl.HelloBeanInstanceFactory"/﹥   
      ﹤bean id="sayhello" factory-bean="factory" factory-method="createHelloBean"/﹥
例:
工厂类:

package com.briup.bean;

import java.io.InputStream;
import java.util.Properties;

/*
 * 实例工厂:
 * new InstanceFactory().getDao();
 */
public class InstanceFactory {
	private String name;
public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

public UserDao getDao() {
	//每次都要构建properties读取文件
	Properties pro=null;
	System.out.println(name+"---");
	UserDao dao=null;
	try {
			pro=new Properties();
		//pro.load(new FileReader("src/com/briup/IOC/us.properties"));
		//相对当前位置读取文件
			InputStream is=
		staticFactory.class.getResourceAsStream("../IOC/us.properties");
			pro.load(is);
		    dao=(UserDao) Class.forName(pro.getProperty("dao")).newInstance();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} 
	return dao;
	
	
}
}
properties文件同上

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
          http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 实例工厂的调用
     1.先构建对象 factory=Class.forName="com.briup.bean.InstanceFactory"
     .newInstance();-->
<bean name="factory" class="com.briup.bean.InstanceFactory">
<!-- 传参要在构建对象是传参 -->
<property name="name" value="tomjake"></property>
</bean>
<!-- 2.调用工厂中的方法(普通方法)
     ud=factory.getDao(); -->
<bean name="ud" factory-bean="factory" factory-method="getDao"></bean>
</beans>



测试代码:

@Test
	public void instanceF_test() {
//			InstanceFactory inf=new InstanceFactory();
//			UserDao dao=inf.getDao();
//			System.out.println(dao);
			try {
				ClassPathXmlApplicationContext cp=
						new ClassPathXmlApplicationContext("com/briup/IOC/instanceF.xml");
				  System.out.println(cp.getBean("ud"));
			} catch (BeansException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		      
	}

 

4)Bean实现Spring提供FactoryBean接口
接口提供工厂方法和返回构建对象的Class以及是否单例的方法
注意:
 

 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="com/briup/ioc/factory/db.properties"></property>
    </bean>
    <bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="location" value="com/briup/IOC/static.properties"></property>
    </bean>
例:
工厂类:

package com.briup.bean;

import org.springframework.beans.factory.FactoryBean;
/*
 * spring提供的工厂方法构建形式
 * 实现FactoryBean接口
 */
public class SpringFactory implements FactoryBean<String>{
/*
 * 工厂方法
 */
	@Override
	public String getObject() throws Exception {
		// TODO Auto-generated method stub
		return "test...OK";
	}
/*
 * 产生工厂返回对象的镜像
 * 一般不关注该方法
 */
	@Override
	public Class<?> getObjectType() {
		// TODO Auto-generated method stub
		return null;
	}

}


数据库工厂类:

package com.briup.bean;

import java.sql.Connection;
import java.sql.DriverManager;

import org.springframework.beans.factory.FactoryBean;

public class ConnectionFactory implements FactoryBean<Connection>{
    private String driver;
    private String url;
    private String user;
    private String passwd;
    
	public String getDriver() {
		return driver;
	}

	public void setDriver(String driver) {
		this.driver = driver;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPasswd() {
		return passwd;
	}

	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}

	@Override
	public Connection getObject() throws Exception {
		// TODO Auto-generated method stub
		Class.forName(driver);
		return DriverManager.getConnection(url, user, passwd);
	}

	@Override
	public Class<?> getObjectType() {
		// TODO Auto-generated method stub
		return null;
	}

}


dp.properties文件


driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:XE
user=jd1812
passwd=briup


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
          http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- spring会自动判断class是不是
     FactoryBean的实现类,是直接调用getObject()返回对象 -->
<bean name="str" class="com.briup.bean.SpringFactory">
</bean>

<!-- 读取properties配置文件,装入内存
     在使用的地方取${key} -->
     <!-- <bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
      <property name="location" value="com/briup/IOC/db.properties"></property>
     </bean> -->
      <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <!-- <property name="location" value="com/briup/IOC/db.properties"></property> -->
      <property name="locations">
      <value>com/briup/IOC/db.properties</value>
      </property>
     </bean>
<bean name="conn" class="com.briup.bean.ConnectionFactory">
<property name="driver" value="${driver}"></property>
<property name="url" value="${url}"></property>
<property name="user" value="${user}"></property>
<property name="passwd" value="${passwd}"></property>
</bean>
</beans>


测试代码:

@Test
	public void springF_test() {
//			InstanceFactory inf=new InstanceFactory();
//			UserDao dao=inf.getDao();
//			System.out.println(dao);
			try {
				ClassPathXmlApplicationContext cp=
						new ClassPathXmlApplicationContext("com/briup/IOC/springF.xml");
				  System.out.println(cp.getBean("str"));
				  System.out.println(cp.getBean("conn"));
			} catch (BeansException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		      
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值