java_spring_实例化bean的3种方法

时间:2021-01-28 20:55:53

//Dao类

package com.dao.bean.www;

public interface PersonServiceDao {

	public abstract void save();

}

//Bean

package com.bean.www;

import com.dao.bean.www.PersonServiceDao;

public class PersonServiceBean implements PersonServiceDao {

	@Override
public void save() {
System.out.println("method save()");
}
}

//第二第三种需要的工厂方法

package com.factory.www;

import com.bean.www.PersonServiceBean;

public class PersonServiceFactory {
public static PersonServiceBean creatBean() {
return new PersonServiceBean();
} public PersonServiceBean creatBean2() {
return new PersonServiceBean();
} }

//配置文件

<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- 获取bean -->
<bean id="personService" class="com.bean.www.PersonServiceBean"></bean> <!-- 静态工厂方法 -->
<bean id="beanFactory1" class="com.factory.www.PersonServiceFactory" factory-method="creatBean" ></bean> <!-- 非静态工厂方法 1.首先实例化工厂类bean -->
<bean id="beanFactory2" class="com.factory.www.PersonServiceFactory" ></bean>
<bean id="GetBean" factory-bean="beanFactory2" factory-method="creatBean2" ></bean>
</beans>

//测试类

package com.itcast.www;

import static org.junit.Assert.*;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.dao.bean.www.PersonServiceDao; public class TestCaseDemo { @BeforeClass
public static void setUpBeforeClass() throws Exception {
} @Test
public void instanceSpring() { ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml"); // PersonServiceDao personService = (PersonServiceDao) ctx
// .getBean("personService");
// PersonServiceDao personService = (PersonServiceDao) ctx
// .getBean("beanFactory1");
PersonServiceDao personService = (PersonServiceDao) ctx
.getBean("GetBean");
personService.save(); } }

//************************初始化和构造函数******************************

package com.bean.www;

import com.dao.bean.www.PersonServiceDao;
/*
* 初始化方法执行在构造方法之后
* 需要在配置文件中配置初始化或者销毁方法
* 用于打开或者关闭资源等
* 单实例-lazy-init=true 获取容器后创建
* lazy-init=false ctx.getbean实现
* 直到关闭才执行destroy方法
* 关闭方法 ctx.close();
* */
public class PersonServiceBean implements PersonServiceDao { public void init(){
System.out.println("init..................");
} @Override
public void save() {
System.out.println("method save()");
} public void destroy(){
System.out.println("destroy..................");
}
}

//配置文件

<bean id="personService" class="com.bean.www.PersonServiceBean" lazy-init="false" init-method="init" destroy-method=""></bean>