java中的spring框架(1)
阿新 • • 發佈:2019-01-07
spring框架主要有IOC程式設計和AOP程式設計
IOC大概講的就是 對類的生成和銷燬,由spring來進行管理,實際上就是第一個xml檔案來進行管理,不用自己來new 一個物件 其中有一個思想就是依賴注入,就是在xml檔案中 某一個類插入到另一個類中。AOP程式設計主要是由spring來管理開發中經常用到的日誌管理和一些常用的東西等,不用自己每次都打一遍
spring框架主要有兩個包,一個是spring包 還有一個是common包
建立一個普通的java專案 在其中創鍵lib資料夾 隨後匯入這些包,選中專案名,隨後右鍵config build path 匯入這些包即可
建立檔案 在src下建立com.tutorialspoint類 隨後建立HelloWorld.java和MainApp類 在helloWorld中編寫如下程式碼
package com.tutorialspoint;
public class HelloWorld {
private String message;
public void getMessage() {
System.out.print("Your Message: " + message);
}
public void setMessage(String message) {
this.message = message;
}
}
隨後在Beans.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-3.0.xsd"> <!--id 和 class這個是必須的 --> <bean id="helloWorld" class="com.tutorialspoint.HelloWorld"> <property name="message" value="Hello World!"/> </bean> <bean id = "helloIndia" class="com.tutorialspoint.HelloWorld" parent="helloWorld"> </bean> </beans>
最核心的就是<bean></bean>中的資訊 id 表明bean的類,class表示包名 隨後property來設定這個類中的屬性
隨後在mainApp中來進行呼叫
package com.tutorialspoint; import org.springframework.context.ApplicationContext; //建立beanFactory的配置檔案 import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { // //獲取配置的上下文 // ApplicationContext context = // new ClassPathXmlApplicationContext("Beans.xml"); // //獲取bean // HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); // obj.getMessage(); //生成工廠 得到配置檔案 依賴注入來提供支援 XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("Beans.xml")); //獲得所需的bean HelloWorld obj = (HelloWorld) factory.getBean("helloWorld"); obj.getMessage(); } }
有兩種方法來進行呼叫 第一種是獲得上下文 context Beans.xml中是配置資訊的檔案 第二種是用BeanFactory這個類獲取 不過這個類好像已經淘汰了
最後執行工程 即可成功