Spring入门

xiaoxiao2026-08-05  5

1.进入springframework.org站点下载spring-framework-2.5.0-with-dependencies.zip并解压缩. 2.右击项目名,选择properties-->Java Build Path,并切换到"Libraries"标签页面,点击"Add External JARS..."将解压后的spring- framework-2.5文件中的dist/modules/spring-core.jar和spring-beans.jar及lib/jakarta-commons/commons-logging.jar加入. 3.写一个最简单的例子 <1>.Java代码 package myspring; public interface DeviceWriter { public void saveData(); } package myspring; public class UsbDiskWriter implements DeviceWriter { public void saveData(){ System.out.println("存储至USB!"); } } package myspring; public class HelloBean { private String helloWord; private DeviceWriter writer; public String getHelloWord() { return helloWord; } public void setHelloWord(String helloWord) { this.helloWord = helloWord; } public DeviceWriter getDeviceWriter() { return writer; } public void setDeviceWriter(DeviceWriter writer) { this.writer = writer; } public void saveData(){ writer.saveData(); } } <2>.配置文件(存放目录:WEB-INF/classes/beans-config.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="writer" class="myspring.UsbDiskWriter"/> <bean id="helloBean" class="myspring.HelloBean"> <property name="helloWord"> <value>Hello! Nice to see you.</value> <!-- 注入String --> </property> <property name="deviceWriter"> <ref bean="writer"/> <!-- 注入自定义类(UsbDiskWriter) --> </property> </bean> </beans> <3>.测试 package myspring; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; public class SpringDemo { public static void main(String[] args){ Resource res = new ClassPathResource("beans-config.xml"); BeanFactory factory = new XmlBeanFactory(res); HelloBean hb = (HelloBean)factory.getBean("helloBean"); // 通过配置文件中的bean的id实例化一个对象 System.out.println("Output: "+hb.getHelloWord()); // Output: Hello! Nice to see you. hb.saveData(); // 存储至USB! } } 相关资源:Spring入门经典
转载请注明原文地址: https://www.6miu.com/read-5050709.html

最新回复(0)