“好記性,不如爛筆頭”。今天正式接觸了Spring框架,第一次接觸Spring框架感覺Spring框架簡化了好多程序代碼,開發效率大大提高。現在介紹使用Spring框架的步驟。(使用spring-framework-2.5.6版本)
1、導入jar包:找到壓縮包里邊的dist/Spring.jar;然后再找到 lib/jakarta-commons/commons-logging.jar
2、編寫spring配置文件....;添加一個bean(將一個類/依賴對象交給spring來維護和創建)
<?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.5.xsd"> <!-- bean:將一個類交給spring維護和創建就是一個bean 之前手動new的對象現在交給spring來做 --> <!--<bean id="springioc" class="com.msit.spring.IOC.DI.ObjectRef.SpringIOC"></bean>--> <!-- bean:就是一個類(對象) property:代表類或者對象中的屬性;name跟類中的屬性名稱一樣;value就相當于= SpringIOC.msg = "Hello-Spring" --> <bean id="hellospring" class="com.msit.spring.IOC.DI.propertity.HelloSpring"> <property name="msg" value="Hello-Spring"></property> </bean> </beans>
3、通過applicationContext context = new ClassPathXMLApplicationContext("applicationContext.xml");context.getBean("bean名稱");來獲取創建的bean
package com.msit.spring.IOC.createObject;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test { public static void main(String[] args) { // 加載配置文件 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //得到Bean HelloWorld ch = (HelloWorld) context.getBean("hellospring"); ch.hello(); //ch.createhello().hello(); //CreateHelloWorld.createhello().hello(); }}
新聞熱點
疑難解答