基于Eclipse的spring+Apache+mysql的开发

来源:互联网 发布:买宠物的软件 编辑:程序博客网 时间:2024/06/09 23:10

1.新建spring工程后,在src里添加javabean的实现类代码,可以是任意功能的实现。

2.然后添加xml配置文件

内容格式(package.setting.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-2.0.xsd">
<bean id="beanid1"/*用于让应用程序访问class对应类的id标识*/ class="package1.classname1"/*对应src里的已经实现的类名*/>//需要访问的类设置
<property name="property1" value="value1"/>//对类中属性的设置,对应的类中必须要有setproperty1()函数的实现才能使用。
<property name="property2" value="value2"/>//功能如上,需要说明的是不管property是什么类型,value的值都需要使用引号
</bean>
<bean id="beanid2" class="package2.classname2">
<property name="property1" value="value1"></property>
<property name="property2" value=" value2"></property>
</bean>
</beans>


3.应用程序的调用方式

package parent.here;


import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;


public class classApp {


public static void main(String[] args) {
try{
BeanFactory factory=new XmlBeanFactory(new ClassPathResource("./package/setting.xml"));//注意引号里xml配置文件的路径要与2所述的xml文件的路径一致
classname1 instance1=(classname1 ) factory.getBean("beanid1");//classname1要是xml配置文件里beanid1对应类的名称

                instance1.method1();//这里的method1必须是在classname1里已经实现的方法。

classname2instance2=(classname2) factory.getBean("beanid2");
instance2.method1();

                instance2.method2();

}catch(Exception e)
{
System.out.print(e.toString());
}
}
}

4.然后运行应用程序就能得到预期的结果。

0 0