锘??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鏂規(guī)硶
}
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) {
// 浠巗pring 瀹瑰櫒涓緱鍒版鍦ㄧ鐞嗙殑sessionFactory,persist鏂規(guī)硶鐢ㄤ簬淇濆瓨瀹炰綋
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="" />
<!-- 榪炴帴姹犲惎鍔ㄦ椂鐨勫垵濮嬪?-->
<property name="initialSize" value="1" />
<!-- 榪炴帴姹犵殑鏈澶у?-->
<property name="maxActive" value="500" />
<!-- 鏈澶х┖闂插?褰撶粡榪囦竴涓珮宄版椂闂村悗錛岃繛鎺ユ睜鍙互鎱㈡參灝嗗凡緇忕敤涓嶅埌鐨勮繛鎺ユ參鎱㈤噴鏀句竴閮ㄥ垎錛屼竴鐩村噺灝戝埌maxIdle涓烘 -->
<property name="maxIdle" value="2" />
<!-- 鏈灝忕┖闂插?褰撶┖闂茬殑榪炴帴鏁板皯浜庨榾鍊兼椂錛岃繛鎺ユ睜灝變細(xì)棰勭敵璇峰幓涓浜涜繛鎺ワ紝浠ュ厤媧嘲鏉ユ椂鏉ヤ笉鍙?qiáng)鐢宠?-->
<property name="minIdle" value="1" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" /><!-- 灝哾atasource娉ㄥ叆鍒皊essionFactory -->
<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()")//瀹氫箟鏈緇堥氱煡
public void doReleaseAction() {
}
@Around("anyMethod()")//鐜粫閫氱煡
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
return pjp.proceed();
}
}
鍩轟簬鍩轟簬XML閰嶇疆鏂瑰紡澹版槑鍒囬潰
public class LogPrint {
public void doAccessCheck() {}瀹氫箟鍓嶇疆閫氱煡
public void doReturnCheck() {}瀹氫箟鍚庣疆閫氱煡
public void doExceptionAction() {}瀹氫箟渚嬪閫氱煡
public void doReleaseAction() {}瀹氫箟鏈緇堥氱煡
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>
緇勬垚 Spring 妗嗘灦鐨勬瘡涓ā鍧楋紙鎴栫粍浠訛級閮藉彲浠ュ崟鐙瓨鍦紝鎴栬呬笌鍏朵粬涓涓垨澶氫釜妯″潡鑱斿悎瀹炵幇銆傛瘡涓ā鍧楃殑鍔熻兘濡備笅錛?
BeanFactory
錛屽畠鏄伐鍘傛ā寮忕殑瀹炵幇銆?code>BeanFactory 浣跨敤鎺у埗鍙嶈漿 錛圛OC錛?妯″紡灝嗗簲鐢ㄧ▼搴忕殑閰嶇疆鍜屼緷璧栨ц鑼冧笌瀹為檯鐨勫簲鐢ㄧ▼搴忎唬鐮佸垎寮銆?
Spring 妗嗘灦鐨勫姛鑳藉彲浠ョ敤鍦ㄤ換浣?J2EE 鏈嶅姟鍣ㄤ腑錛屽ぇ澶氭暟鍔熻兘涔熼傜敤浜庝笉鍙楃鐞嗙殑鐜銆係pring 鐨勬牳蹇冭鐐規(guī)槸錛氭敮鎸佷笉緇戝畾鍒扮壒瀹?J2EE 鏈嶅姟鐨勫彲閲嶇敤涓氬姟鍜屾暟鎹闂璞°傛鏃犵枒闂紝榪欐牱鐨勫璞″彲浠ュ湪涓嶅悓 J2EE 鐜 錛圵eb 鎴?EJB錛夈佺嫭绔嬪簲鐢ㄧ▼搴忋佹祴璇曠幆澧冧箣闂撮噸鐢ㄣ?
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;
}
}
嫻嬭瘯綾伙細(xì)
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鐨剆ava鏂規(guī)硶錛岃緭鍑虹粨鏋?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("榪欐槸personDaoBean鐨凙dd()鏂規(guī)硶");
}
}
/**
* 瀹炵幇鐨剆pring瀹瑰櫒
*
* @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);// 璋冪敤 璇誨彇閰嶇疆鏂囦歡 鐨勬柟娉?br />
this.instanceBeans();// 璋冪敤bean鐨勫疄渚嬪寲
this.injectObject();// 娉ㄥ叆瀵硅薄
}
/**
* 涓篵ean瀵硅薄鐨勫睘鎬ф敞鍏ュ?br />
*/
private void injectObject() {
for (BeanDefinition beanDefinition : beanDefines) {
Object bean = sigletons.get(beanDefinition.getId());
if (bean != null) {
// 鍙栧緱灞炴ф弿榪?錛屾槸涓涓暟緇?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鏂規(guī)硶.
// private
if (setter != null) {
Object value=null;
if(propertyDefinition.getRef()!=null && !"".equals(propertyDefinition.getRef().trim())){
value = sigletons
.get(propertyDefinition
.getRef());
}else{
//灝嗛厤緗枃浠墮噷瀛楃涓茬被鍨嬭漿鎹負(fù)灞炴х被鍨嬬殑鍊?
value=ConvertUtils.convert(propertyDefinition.getValue(), properdesc.getPropertyType());
}
setter.setAccessible(true);// 璁劇疆涓哄彲璁塊棶
setter.invoke(bean, value);// 鎶婂紩鐢ㄥ璞℃敞鍏ュ埌灞炴?br />
}
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 瀹屾垚bean鐨勫疄渚嬪寲
*/
private void instanceBeans() {
// System.out.println("bean瀹炰緥鍖栨柟娉曡璋冪敤");
// 鍒╃敤鍙嶅皠鏈哄埗鎶奲ean瀹炰緥鍖?br />
for (BeanDefinition beanDefinition : beanDefines) {
try {
// 鍒ゆ柇BeanDefinition鐨勫疄渚嬭幏寰楃殑綾誨悕涓嶄負(fù)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();
}
}
}
/**
* 璇誨彇閰嶇疆鏂囦歡淇℃伅
*
* @param filename
*/
private void readXml(String filename) {
// System.out.println("璇誨彇xml鏂囦歡鐨勬柟娉曡璋冪敤浜?);
SAXReader saxReader = new SAXReader();// 鍒涘緩璇誨彇鍣?br />
Document document = null;
try {
URL xmlpath = this.getClass().getClassLoader()
.getResource(filename);//鍙栧緱褰撳墠xml鏂囦歡鍦ㄦ湰鍦扮殑浣嶇疆
document = saxReader.read(xmlpath);// 璇誨彇璺緞
Map<String, String> nsMap = new HashMap<String, String>();
nsMap.put("ns", "http://www.springframework.org/schema/beans");// 鍔犲叆鍛藉悕絀洪棿
XPath xsub = document.createXPath("http://ns:beans/ns:bean");// 鍒涘緩beans/bean鏌ヨ璺緞
xsub.setNamespaceURIs(nsMap);// 璁劇疆鍛藉悕絀洪棿
List<Element> beans = xsub.selectNodes(document);// 鑾峰彇鏂囨。涓嬫墍鏈塨ean鑺傜偣
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);// 璁劇疆鍛藉悕絀洪棿
List<Element> propertys = propertysub.selectNodes(element);// 鏌ユ壘鑺傜偣
for (Element property : propertys) {
String propertyName = property.attributeValue("name");// 鍙栧緱property鐨刵ame鍊?br />
String propertyref = property.attributeValue("ref");// 鍙栧緱property鐨剅ef鍊?br />
String propertyValue = property.attributeValue("value");// 鍙栧緱property鐨剉alue鍊?/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
榪欐槸personDaoBean鐨凙dd()鏂規(guī)硶
/**
* 瀹炵幇鐨剆pring瀹瑰櫒
*
* @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);// 璋冪敤 璇誨彇閰嶇疆鏂囦歡 鐨勬柟娉?br />
this.instanceBeans();// 璋冪敤bean鐨勫疄渚嬪寲
this.injectObject();// 娉ㄥ叆瀵硅薄
}
/**
* 涓篵ean瀵硅薄鐨勫睘鎬ф敞鍏ュ?br />
*/
private void injectObject() {
for (BeanDefinition beanDefinition : beanDefines) {
Object bean = sigletons.get(beanDefinition.getId());
if (bean != null) {
// 鍙栧緱灞炴ф弿榪?錛屾槸涓涓暟緇?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鏂規(guī)硶.
// private
if (setter != null) {
Object value = sigletons
.get(propertyDefinition.getRef());
setter.setAccessible(true);// 璁劇疆涓哄彲璁塊棶
setter.invoke(bean, value);// 鎶婂紩鐢ㄥ璞℃敞鍏ュ埌灞炴?br />
}
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 瀹屾垚bean鐨勫疄渚嬪寲
*/
private void instanceBeans() {
// System.out.println("bean瀹炰緥鍖栨柟娉曡璋冪敤");
// 鍒╃敤鍙嶅皠鏈哄埗鎶奲ean瀹炰緥鍖?br />
for (BeanDefinition beanDefinition : beanDefines) {
try {
// 鍒ゆ柇BeanDefinition鐨勫疄渚嬭幏寰楃殑綾誨悕涓嶄負(fù)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();
}
}
}
/**
* 璇誨彇閰嶇疆鏂囦歡淇℃伅
*
* @param filename
*/
private void readXml(String filename) {
// System.out.println("璇誨彇xml鏂囦歡鐨勬柟娉曡璋冪敤浜?);
SAXReader saxReader = new SAXReader();// 鍒涘緩璇誨彇鍣?br />
Document document = null;
try {
URL xmlpath = this.getClass().getClassLoader()
.getResource(filename);//鍙栧緱褰撳墠xml鏂囦歡鍦ㄦ湰鍦扮殑浣嶇疆
document = saxReader.read(xmlpath);// 璇誨彇璺緞
System.out.println(document);
Map<String, String> nsMap = new HashMap<String, String>();
nsMap.put("ns", "http://www.springframework.org/schema/beans");// 鍔犲叆鍛藉悕絀洪棿
XPath xsub = document.createXPath("http://ns:beans/ns:bean");// 鍒涘緩beans/bean鏌ヨ璺緞
xsub.setNamespaceURIs(nsMap);// 璁劇疆鍛藉悕絀洪棿
List<Element> beans = xsub.selectNodes(document);// 鑾峰彇鏂囨。涓嬫墍鏈塨ean鑺傜偣
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);// 璁劇疆鍛藉悕絀洪棿
List<Element> propertys = propertysub.selectNodes(element);// 鏌ユ壘鑺傜偣
for (Element property : propertys) {
String propertyName = property.attributeValue("name");// 鍙栧緱property鐨刵ame鍊?br />
String propertyref = property.attributeValue("ref");// 鍙栧緱property鐨剅ef鍊?/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鏂規(guī)硶
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鏂規(guī)硶
}
package cn.itcast.dao.impl;
import cn.itcast.dao.IPersonDao;
public class PersonDaoBean implements IPersonDao {
public void add(){
System.out.println("榪欐槸personDaoBean鐨凙dd()鏂規(guī)硶");
}
}
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("榪欐槸personDaoBean鐨凙dd()鏂規(guī)硶");
}
}
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鏂規(guī)硶");
}
public void cleanup(){
System.out.println("cleanup鏂規(guī)硶");
}
}
<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
鍦ㄦ瘡涓猄pring IoC瀹瑰櫒涓竴涓猙ean瀹氫箟鍙湁涓涓璞″疄渚嬨傞粯璁ゆ儏鍐典笅浼?xì)鍦ㄥ鍣ㄥ惎鍔ㄦ椂鍒濆鍖朾ean錛屼絾鎴戜滑鍙互鎸囧畾Bean鑺傜偣鐨刲azy-init=“true”鏉ュ歡榪熷垵濮嬪寲bean錛岃繖鏃跺欙紝鍙湁絎竴嬈¤幏鍙朾ean浼?xì)鎵嶅垵濮嬪寲bean銆傚錛?br />
<bean id="xxx" class="cn.itcast.OrderServiceBean" lazy-init="true"/>
濡傛灉鎯沖鎵鏈塨ean閮藉簲鐢ㄥ歡榪熷垵濮嬪寲錛屽彲浠ュ湪鏍硅妭鐐筨eans璁劇疆default-lazy-init=“true“錛屽涓嬶細(xì)
<beans default-lazy-init="true“ ...>
.prototype
姣忔浠庡鍣ㄨ幏鍙朾ean閮芥槸鏂扮殑瀵硅薄銆?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瀹瑰櫒榛樿鐨刡ean鐨勪駭鐢熸柟寮忔槸鍗曚緥
鏀?/span>
<bean id="persionServiceBean" class="cn.com.xinli.service.impl.PersionServiceBean" scope="prototype"></bean>
榪欐椂鍊欒緭鍑猴細(xì)false ,鏄劇劧ps涓巔s2灝變笉涓鏍楓?br />
1.浣跨敤綾繪瀯閫犲櫒瀹炰緥鍖?/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 :鍖呭惈宸ュ巶綾葷被鍚嶅拰浜х敓涓氬姟bean鐨勬柟娉曞悕瀛?/span>
<bean id="persionServiceBean2" class="cn.com.xinli.service.impl.PersionServiceBeanFactory" factory-method="createPersionServiceBean"/>
(3) 嫻嬭瘯
(4) 緇撴灉
2009-05-24 14:34:00,781 INFO (PersionServiceBean.java:12) - 鎴戞槸save()鏂規(guī)硶!
3.浣跨敤瀹炰緥宸ュ巶鏂規(guī)硶瀹炰緥鍖?
<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 :鍐欎袱涓猙ean,涓涓槸宸ュ巶bean,涓涓槸鍒╃敤宸ュ巶bean浜х敓涓氬姟bean鐨刡ean.
(3) 嫻嬭瘯
(4) 緇撴灉
2009-05-24 14:49:17,812 INFO (PersionServiceBean.java:12) - 鎴戞槸save()鏂規(guī)硶!
(5) 娉ㄦ剰,鍏跺疄鏂瑰紡2鍜屾柟寮?鐨勫尯鍒氨鍦?宸ュ巶綾諱腑鏄浣曚駭鐢熶笟鍔ean鐨?鏂瑰紡2鏄?span style="color: #ff0000">static鏂瑰紡,鏂瑰紡3涓嶆槸