??xml version="1.0" encoding="utf-8" standalone="yes"?>
public class Person {
private Integer id;
private String name;
public Person(){
}
public Person(String name) {
this.name=name;
}
getter&&setterҎ
}
Person.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.itcast.bean">
<class name="Person" table="person">
<id name="id" type="integer">
<generator class="native"></generator>
</id>
<property name="name" length="10" not-null="true">
</property>
</class>
</hibernate-mapping>
定义业务接口package cn.itcast.service;
import java.util.List;
import cn.itcast.bean.Person;
public interface IPersonService {
/**
* 保存人员信息
* @param person
*/
public abstract void save(Person person);
/**
* 更新信息
* @param person
*/
public abstract void update(Person person);
/**
* 获取人员
* @param personId
* @return
*/
public abstract Person getPerson(Integer personId);
/**
* 删除人员信息
* @param personId
*/
public abstract void delete(Integer personId);
/**
* 获取人员列表
* @return
*/
public abstract List<Person> getPersons();
}
package cn.itcast.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cn.itcast.bean.Person;
import cn.itcast.service.IPersonService;
/**
* 业务层,采用注解声明事务
*
* @author Administrator
*
*/
@Transactional
public class PersonServiceBean implements IPersonService {
@Resource
private SessionFactory sessionFactory;
public void save(Person person) {
// 从spring 容器中得到正在管理的sessionFactory,persistҎ用于保存实体
sessionFactory.getCurrentSession().persist(person);
}
public void update(Person person) {
sessionFactory.getCurrentSession().merge(person);
}
@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
public Person getPerson(Integer personId) {
return (Person) sessionFactory.getCurrentSession().get(Person.class,
personId);
}
public void delete(Integer personId) {
sessionFactory.getCurrentSession()
.delete(
sessionFactory.getCurrentSession().load(Person.class,
personId));
}
@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
@SuppressWarnings("unchecked")
public List<Person> getPersons() {
return sessionFactory.getCurrentSession().createQuery("from Person")
.list();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!--
- Application context definition for JPetStore's business layer.
- Contains bean references to the transaction manager and to the DAOs in
- dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation").
-->
<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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
<!-- 配置数据?-->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName"
value="org.gjt.mm.mysql.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="" />
<!-- q接池启动时的初始?-->
<property name="initialSize" value="1" />
<!-- q接池的最大?-->
<property name="maxActive" value="500" />
<!-- 最大空闲?当经q一个高峰时间后Q连接池可以慢慢已l用不到的连接慢慢释放一部分Q一直减到maxIdle为止 -->
<property name="maxIdle" value="2" />
<!-- 最空闲?当空闲的q接数少于阀值时Q连接池׃预申请去一些连接,以免z峰来时来不及申?-->
<property name="minIdle" value="1" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" /><!-- datasource注入到sessionFactory -->
<property name="mappingResources">
<list>
<value>cn/itcast/bean/Person.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=update hibernate.show_sql=false
hibernate.format_sql=false
</value>
</property>
</bean>
<!-- 通过事务理 理sessionFactory -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<bean id="personServiceBean"
class="cn.itcast.service.impl.PersonServiceBean">
</bean>
</beans>
package junit;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.bean.Person;
import cn.itcast.service.IPersonService;
public class IPersonServiceTest {
private static IPersonService ipersonservice;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
ipersonservice=(IPersonService)ctx.getBean("personServiceBean");
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void TestSave(){
ipersonservice.save(new Person("张"));
System.out.println("保存成功");
}
@Test public void testGetPerson(){
Person person=ipersonservice.getPerson(1);
System.out.println(person.getName());
}
@Test public void testUpdate(){
Person person=ipersonservice.getPerson(1);
person.setName("丽");
ipersonservice.update(person);
}
@Test public void testGetPersons(){
List<Person> persons=ipersonservice.getPersons();
for(Person person : persons){
System.out.println(person.getId()+" :" +person.getName());
}
}
@Test public void testDelete(){
ipersonservice.delete(1);
}
}
table :person
id int
name varchar
@Aspect
public class LogPrint {
@Pointcut("execution(* cn.itcast.service..*.*(..))")
private void anyMethod() {}//声明一个切入点
@Before("anyMethod() && args(userName)")//定义前置通知
public void doAccessCheck(String userName) {
}
@AfterReturning(pointcut="anyMethod()",returning="revalue")//定义后置通知
public void doReturnCheck(String revalue) {
}
@AfterThrowing(pointcut="anyMethod()", throwing="ex")//定义例外通知
public void doExceptionAction(Exception ex) {
}
@After("anyMethod()")//定义最l通知
public void doReleaseAction() {
}
@Around("anyMethod()")//环绕通知
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
return pjp.proceed();
}
}
ZZXML配置方式声明切面
public class LogPrint {
public void doAccessCheck() {}定义前置通知
public void doReturnCheck() {}定义后置通知
public void doExceptionAction() {}定义例外通知
public void doReleaseAction() {}定义最l通知
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
return pjp.proceed();环绕通知
}
}
<bean id="orderservice" class="cn.itcast.service.OrderServiceBean"/>
<bean id="log" class="cn.itcast.service.LogPrint"/>
<aop:config>
<aop:aspect id="myaop" ref="log">
<aop:pointcut id="mycut" expression="execution(* cn.itcast.service..*.*(..))"/>
<aop:before pointcut-ref="mycut" method="doAccessCheck"/>
<aop:after-returning pointcut-ref="mycut" method="doReturnCheck "/>
<aop:after-throwing pointcut-ref="mycut" method="doExceptionAction"/>
<aop:after pointcut-ref="mycut" method=“doReleaseAction"/>
<aop:around pointcut-ref="mycut" method="doBasicProfiling"/>
</aop:aspect>
</aop:config>
l成 Spring 框架的每个模块(或组Ӟ都可以单独存在,或者与其他一个或多个模块联合实现。每个模块的功能如下Q?
BeanFactory
Q它是工厂模式的实现?code>BeanFactory 使用控制反{ QIOCQ?模式应用程序的配置和依赖性规范与实际的应用程序代码分开?
Spring 框架的功能可以用在Q?J2EE 服务器中Q大多数功能也适用于不受管理的环境。Spring 的核心要ҎQ支持不l定到特?J2EE 服务的可重用业务和数据访问对象。毫无疑问,q样的对象可以在不同 J2EE 环境 QWeb ?EJBQ、独立应用程序、测试环境之间重用?
public abstract void Save();
public Set<String> getSets() ;
public List<String> getLists() ;
public Properties getProperties() ;
public Map<String, String> getMaps() ;
}
public class PersonServiceBean implements IPersonService {
private IPersonDao iPersonDao;
private Set<String> sets=new HashSet<String>();
private List<String> lists=new ArrayList<String>();
private Properties properties=new Properties();
private Map<String,String> maps=new HashMap<String,String>();
public PersonServiceBean(IPersonDao personDao, String name) {
iPersonDao = personDao;
this.name = name;
}
public void Save(){
System.out.println(name);//输出name
iPersonDao.add();
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, String> getMaps() {
return maps;
}
public void setMaps(Map<String, String> maps) {
this.maps = maps;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public Set<String> getSets() {
return sets;
}
public void setSets(Set<String> sets) {
this.sets = sets;
}
public IPersonDao getIPersonDao() {
return iPersonDao;
}
public void setIPersonDao(IPersonDao personDao) {
iPersonDao = personDao;
}
public List<String> getLists() {
return lists;
}
public void setLists(List<String> lists) {
this.lists = lists;
}
}
试c:
public class SpringTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void instanceSpring() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"beans.xml");
// ItcastClassPathXMLApplicationContext ctx=new
// ItcastClassPathXMLApplicationContext("beans.xml");
//
IPersonService ipersonService = (IPersonService) ctx
.getBean("personService");
//集合对象的遍?br />
System.out.println("===========set==================");
for (String value : ipersonService.getSets()) {
System.out.println(value);
}
// ipersonService.Save();
// ctx.close();
// ctx.registerShutdownHook();
System.out.println("===========List=================");
for(String value:ipersonService.getLists()){
System.out.println(value);
}
System.out.println("=========properties===============");
for(Object value:ipersonService.getProperties().keySet()){
System.out.println(value);
}
System.out.println("================maps==================");
for(Object value:ipersonService.getMaps().keySet()){
System.out.println(value);
}
//调用PersonServiceBean的savaҎQ输出结?br />
ipersonService.Save();
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="personService"
class="cn.itcast.service.impl.PersonServiceBean">
<property name="IPersonDao" ref="personDaoBean"></property>
<constructor-arg index="0" ref="personDaoBean"
type="cn.itcast.dao.IPersonDao" />
<constructor-arg index="1" type="java.lang.String"
value="传智博客">
</constructor-arg>
<property name="sets">
<set>
<value>set1</value>
<value>set2</value>
<value>set3</value>
</set>
</property>
<property name="lists">
<list>
<value>list1</value>
<value>list2</value>
<value>list3</value>
</list>
</property>
<property name="properties">
<props>
<prop key="properties1">property1</prop>
<prop key="properties2">property2</prop>
<prop key="properties3">property3</prop>
</props>
</property>
<property name="maps">
<map>
<entry key="key1" value="keyFirst"></entry>
<entry key="key2" value="keySecond"></entry>
<entry key="key3" value="keyThird"></entry>
</map>
</property>
</bean>
<bean id="personDaoBean" class="cn.itcast.dao.impl.PersonDaoBean"></bean>
<!--
<bean id="anotherPersonServiceBean"
class="cn.itcast.service.impl.AnotherPersonServiceBean" >
</bean>
-->
</beans>
public class PersonDaoBean implements IPersonDao {
public void add(){
System.out.println("q是personDaoBean的Add()Ҏ");
}
}
/**
* 实现的spring容器
*
* @author Administrator
*
*/
public class ItcastClassPathXMLApplicationContext {
private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
private Map<String, Object> sigletons = new HashMap<String, Object>();
public ItcastClassPathXMLApplicationContext() {
}
public ItcastClassPathXMLApplicationContext(String filename) {
// System.out.println("构造方?");
this.readXml(filename);// 调用 d配置文g 的方?br />
this.instanceBeans();// 调用bean的实例化
this.injectObject();// 注入对象
}
/**
* 为bean对象的属性注入?br />
*/
private void injectObject() {
for (BeanDefinition beanDefinition : beanDefines) {
Object bean = sigletons.get(beanDefinition.getId());
if (bean != null) {
// 取得属性描q?Q是一个数l?br />
try {
PropertyDescriptor[] ps = Introspector.getBeanInfo(
bean.getClass()).getPropertyDescriptors();
for (PropertyDefinition propertyDefinition : beanDefinition
.getPropertys()) {// 取所有属?br />
for (PropertyDescriptor properdesc : ps) {
if (propertyDefinition.getName().equals(
properdesc.getName())) {
Method setter = properdesc.getWriteMethod();// 获取属性的setterҎ.
// private
if (setter != null) {
Object value=null;
if(propertyDefinition.getRef()!=null && !"".equals(propertyDefinition.getRef().trim())){
value = sigletons
.get(propertyDefinition
.getRef());
}else{
//配|文仉字符串类型{换ؓ属性类型的?
value=ConvertUtils.convert(propertyDefinition.getValue(), properdesc.getPropertyType());
}
setter.setAccessible(true);// 讄为可讉K
setter.invoke(bean, value);// 把引用对象注入到属?br />
}
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 完成bean的实例化
*/
private void instanceBeans() {
// System.out.println("bean实例化方法被调用");
// 利用反射机制把bean实例?br />
for (BeanDefinition beanDefinition : beanDefines) {
try {
// 判断BeanDefinition的实例获得的cd不ؓnull和空?br />
if (beanDefinition.getClassName() != null
&& !"".equals(beanDefinition.getClassName().trim()))
sigletons.put(beanDefinition.getId(), Class.forName(
beanDefinition.getClassName()).newInstance());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* d配置文g信息
*
* @param filename
*/
private void readXml(String filename) {
// System.out.println("dxml文g的方法被调用?);
SAXReader saxReader = new SAXReader();// 创徏d?br />
Document document = null;
try {
URL xmlpath = this.getClass().getClassLoader()
.getResource(filename);//取得当前xml文g在本地的位置
document = saxReader.read(xmlpath);// d路径
Map<String, String> nsMap = new HashMap<String, String>();
nsMap.put("ns", "http://www.springframework.org/schema/beans");// 加入命名I间
XPath xsub = document.createXPath("http://ns:beans/ns:bean");// 创徏beans/bean查询路径
xsub.setNamespaceURIs(nsMap);// 讄命名I间
List<Element> beans = xsub.selectNodes(document);// 获取文档下所有bean节点
for (Element element : beans) {
String id = element.attributeValue("id");// 获取id属性?br />
String clazz = element.attributeValue("class");// 获取class属性?br />
BeanDefinition beanDefine = new BeanDefinition(id, clazz);
XPath propertysub = element.createXPath("ns:property");// 船舰查询路径
propertysub.setNamespaceURIs(nsMap);// 讄命名I间
List<Element> propertys = propertysub.selectNodes(element);// 查找节点
for (Element property : propertys) {
String propertyName = property.attributeValue("name");// 取得property的name?br />
String propertyref = property.attributeValue("ref");// 取得property的ref?br />
String propertyValue = property.attributeValue("value");// 取得property的value?/span>
PropertyDefinition propertyDefinition = new PropertyDefinition(
propertyName, propertyref,propertyValue);
beanDefine.getPropertys().add(propertyDefinition);// 属性对象加入到bean?br />
}
beanDefines.add(beanDefine);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取bean 实例
*
* @param beanName
* @return
*/
public Object getBean(String beanName) {
return this.sigletons.get(beanName);
}
}
public class SpringTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void instanceSpring() {
// ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
// "beans.xml");
ItcastClassPathXMLApplicationContext ctx=new ItcastClassPathXMLApplicationContext("beans.xml");
//
IPersonService ipersonService = (IPersonService)ctx
.getBean("personService");
ipersonService.Save();
// ctx.close();
// ctx.registerShutdownHook();
}
}
public class PropertyDefinition {
private String name;
private String ref;
private String value;
public PropertyDefinition(String name, String ref,String value) {
this.name = name;
this.ref = ref;
this.value=value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
其他略?br />
out:
Itcast
15
q是personDaoBean的Add()Ҏ
/**
* 实现的spring容器
*
* @author Administrator
*
*/
public class ItcastClassPathXMLApplicationContext {
private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
private Map<String, Object> sigletons = new HashMap<String, Object>();
public ItcastClassPathXMLApplicationContext() {
}
public ItcastClassPathXMLApplicationContext(String filename) {
// System.out.println("构造方?");
this.readXml(filename);// 调用 d配置文g 的方?br />
this.instanceBeans();// 调用bean的实例化
this.injectObject();// 注入对象
}
/**
* 为bean对象的属性注入?br />
*/
private void injectObject() {
for (BeanDefinition beanDefinition : beanDefines) {
Object bean = sigletons.get(beanDefinition.getId());
if (bean != null) {
// 取得属性描q?Q是一个数l?br />
try {
PropertyDescriptor[] ps = Introspector.getBeanInfo(
bean.getClass()).getPropertyDescriptors();
for (PropertyDefinition propertyDefinition : beanDefinition
.getPropertys()) {// 取所有属?br />
for (PropertyDescriptor properdesc : ps) {
if (propertyDefinition.getName().equals(
properdesc.getName())) {
Method setter = properdesc.getWriteMethod();// 获取属性的setterҎ.
// private
if (setter != null) {
Object value = sigletons
.get(propertyDefinition.getRef());
setter.setAccessible(true);// 讄为可讉K
setter.invoke(bean, value);// 把引用对象注入到属?br />
}
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 完成bean的实例化
*/
private void instanceBeans() {
// System.out.println("bean实例化方法被调用");
// 利用反射机制把bean实例?br />
for (BeanDefinition beanDefinition : beanDefines) {
try {
// 判断BeanDefinition的实例获得的cd不ؓnull和空?br />
if (beanDefinition.getClassName() != null
&& !"".equals(beanDefinition.getClassName().trim()))
sigletons.put(beanDefinition.getId(), Class.forName(
beanDefinition.getClassName()).newInstance());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* d配置文g信息
*
* @param filename
*/
private void readXml(String filename) {
// System.out.println("dxml文g的方法被调用?);
SAXReader saxReader = new SAXReader();// 创徏d?br />
Document document = null;
try {
URL xmlpath = this.getClass().getClassLoader()
.getResource(filename);//取得当前xml文g在本地的位置
document = saxReader.read(xmlpath);// d路径
System.out.println(document);
Map<String, String> nsMap = new HashMap<String, String>();
nsMap.put("ns", "http://www.springframework.org/schema/beans");// 加入命名I间
XPath xsub = document.createXPath("http://ns:beans/ns:bean");// 创徏beans/bean查询路径
xsub.setNamespaceURIs(nsMap);// 讄命名I间
List<Element> beans = xsub.selectNodes(document);// 获取文档下所有bean节点
System.out.println(beans.size());
for (Element element : beans) {
String id = element.attributeValue("id");// 获取id属性?br />
String clazz = element.attributeValue("class");// 获取class属性?br />
BeanDefinition beanDefine = new BeanDefinition(id, clazz);
System.out.println("id=" + id);
System.out.println("clazz=" + clazz);
XPath propertysub = element.createXPath("ns:property");// 船舰查询路径
propertysub.setNamespaceURIs(nsMap);// 讄命名I间
List<Element> propertys = propertysub.selectNodes(element);// 查找节点
for (Element property : propertys) {
String propertyName = property.attributeValue("name");// 取得property的name?br />
String propertyref = property.attributeValue("ref");// 取得property的ref?/span>
System.out.println(propertyName + "= " + propertyref);
PropertyDefinition propertyDefinition = new PropertyDefinition(
propertyName, propertyref);
beanDefine.getPropertys().add(propertyDefinition);// 属性对象加入到bean?br />
}
beanDefines.add(beanDefine);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取bean 实例
*
* @param beanName
* @return
*/
public Object getBean(String beanName) {
return this.sigletons.get(beanName);
}
}
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
>
<bean id="personService"
class="cn.itcast.service.impl.PersonServiceBean">
<property name="IPersonDao" ref="personDaoBean"></property>
</bean>
<bean id="personDaoBean" class="cn.itcast.dao.impl.PersonDaoBean"></bean>
</beans>
package junit.test;
public class PropertyDefinition {
private String name;
private String ref;
public PropertyDefinition(String name, String ref) {
this.name = name;
this.ref = ref;
}
getter&setter method
}
package junit.test;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import cn.itcast.service.IPersonService;
import cn.itcast.service.impl.PersonServiceBean;
public class SpringTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void instanceSpring() {
// ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
// "beans.xml");
ItcastClassPathXMLApplicationContext ctx=new ItcastClassPathXMLApplicationContext("beans.xml");
IPersonService ipersonService = (IPersonService)ctx
.getBean("personService");//调用自定义容器的getBeanҎ
ipersonService.Save();
// ctx.close();
// ctx.registerShutdownHook();
}
}
package junit.test;
import java.util.ArrayList;
import java.util.List;
public class BeanDefinition {
private String id;
private String className;
private List<PropertyDefinition> propertys=new ArrayList<PropertyDefinition>();
生成getter,setterҎ
}
package cn.itcast.dao.impl;
import cn.itcast.dao.IPersonDao;
public class PersonDaoBean implements IPersonDao {
public void add(){
System.out.println("q是personDaoBean的Add()Ҏ");
}
}
package cn.itcast.service;
public interface IPersonService {
public abstract void Save();
}
package cn.itcast.service.impl;
import cn.itcast.dao.IPersonDao;
import cn.itcast.service.IPersonService;
/**
* 业务bean
* @author Administrator
*
*/
public class PersonServiceBean implements IPersonService {
private IPersonDao iPersonDao;
public IPersonDao getIPersonDao() {
return iPersonDao;
}
public void setIPersonDao(IPersonDao personDao) {
iPersonDao = personDao;
}
public void Save(){
iPersonDao.add();
}
}
public abstract void Save();
}
public class PersonDaoBean implements IPersonDao {
public void add(){
System.out.println("q是personDaoBean的Add()Ҏ");
}
}
public class PersonServiceBean implements IPersonService {
private IPersonDao iPersonDao;
public IPersonDao getIPersonDao() {
return iPersonDao;
}
public void setIPersonDao(IPersonDao personDao) {
iPersonDao = personDao;
}
public void Save(){
iPersonDao.add();
}
}
public void instanceSpring() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"beans.xml");
IPersonService ipersonService = (IPersonService) ctx
.getBean("personService");
ipersonService.Save();
ctx.close();
// ctx.registerShutdownHook();
}
public void init(){
System.out.println("我是初始化函?);
}
public PersonServiceBean(){
System.out.println("我是构造函?);
}
public void Save(){
System.out.println("saveҎ");
}
public void cleanup(){
System.out.println("cleanupҎ");
}
}
<bean id="personService"
class="cn.itcast.service.impl.PersonServiceBean"
init-method="init" destroy-method="cleanup"/>
@Test public void instanceSpring(){
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
IPersonService ipersonService=(IPersonService)ctx.getBean("personService");
ctx.close();
.singleton
在每个Spring IoC容器中一个bean定义只有一个对象实例。默认情况下会在容器启动时初始化beanQ但我们可以指定Bean节点的lazy-init=“true”来gq初始化beanQ这时候,只有W一ơ获取bean会才初始化bean。如Q?br />
<bean id="xxx" class="cn.itcast.OrderServiceBean" lazy-init="true"/>
如果惛_所有bean都应用gq初始化Q可以在根节点beans讄default-lazy-init=“true“Q如下:
<beans default-lazy-init="true“ ...>
.prototype
每次从容器获取bean都是新的对象?br />
.request
.session
.global session
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersionSevice ps=(PersionSevice)ctx.getBean("persionServiceBean");
PersionSevice ps2=(PersionSevice)ctx.getBean("persionServiceBean");
System.out.println(ps==ps2);
输出:true
可见spring容器默认的bean的生方式是单例
?/span>
<bean id="persionServiceBean" class="cn.com.xinli.service.impl.PersionServiceBean" scope="prototype"></bean>
q时候输出:false ,昄ps与ps2׃一栗?br />
1.使用cL造器实例?/span>
<bean id=“orderService" class="cn.itcast.OrderServiceBean"/>
2.使用静态工厂方法实例化
<bean id="persionServiceBean2" class="cn.com.xinli.service.impl.PersionServiceBeanFactory" factory-method="createPersionServiceBean"/>
public class PersionServiceBeanFactory
{
public static PersionServiceBean createPersionServiceBean()
{
return new PersionServiceBean();
}
}
例子:
(1).首先写工厂类.他其中包含生我们的业务bean的方?/span>
(2).改写beans.xml :包含工厂cȝ名和产生业务bean的方法名?/span>
<bean id="persionServiceBean2" class="cn.com.xinli.service.impl.PersionServiceBeanFactory" factory-method="createPersionServiceBean"/>
(3) 试
(4) l果
2009-05-24 14:34:00,781 INFO (PersionServiceBean.java:12) - 我是save()Ҏ!
3.使用实例工厂Ҏ实例?
<bean id="PersionServiceBeanFactory" class="cn.com.xinli.service.impl.PersionServiceBeanFactory"></bean>
<bean id="persionServiceBean3" factory-bean="PersionServiceBeanFactory" factory-method="createPersionServiceBean2"></bean>
public PersionServiceBean createPersionServiceBean2()
{
return new PersionServiceBean();
}
例子:
(1). 首先写工厂类.他其中包含生我们的业务bean的方?nbsp;,在已有代码的基础?/span>
(2).改写beans.xml :写两个bean,一个是工厂bean,一个是利用工厂bean产生业务bean的bean.
(3) 试
(4) l果
2009-05-24 14:49:17,812 INFO (PersionServiceBean.java:12) - 我是save()Ҏ!
(5) 注意,其实方式2和方?的区别就?工厂cM是如何生业务bean?方式2?span style="color: #ff0000">static方式,方式3不是