這次在項目中使用了Spring框架,首先就來總結(jié)下Spring中的配置到最基本的使用悼粮。
準(zhǔn)備工作
首先廢話不多說,寫Spring必須得下載jar包扣猫,這里附上一個Spring 3 jar下載地址
-
這里以idea+mac的開發(fā)環(huán)境為例
? ? ? ? ? a.在idea下創(chuàng)建一個項目
? ? ? ? ? b.在項目下創(chuàng)建一個叫做lib的文件夾并把jar包放到里面
? ? ? ? ? c.把剛剛創(chuàng)建的lib文件夾的jar包添加到環(huán)境中(以mac為例)選擇file-->Project Structure(或者?;)-->Modules-->Dependencies點擊如圖:
+號
? ? ? ? ? 之后選擇剛剛的lib文件夾點擊apply即成功添加入環(huán)境中
創(chuàng)建Spring相關(guān)的配置文件
? ? ? ? a.在src文件夾下創(chuàng)建一個格式如下和xml名字不限(我這里命名為applicationContext.xml)翘地,這是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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
到此Spring的基本配置就結(jié)束了昧穿。
-
在src文件夾下創(chuàng)建如下的package:其中包含一個bean包來存放實體類、一個用來測試的test的包
在bean包下創(chuàng)建一個FirstBean實體類:
package spring.bean;
public class FirstBean {
public void sayHello(){
System.out.println("FirstBean sayHello");
}
}
之后到上一步創(chuàng)建好的applicationContext.xml中進(jìn)行配置
- 在applicationContext.xml中增加一個
<bean>
標(biāo)簽,增加代碼如下:
<bean id="first" class="spring.bean.FirstBean" scope="prototype" > </bean>
屬性:
? ? ? ? ? id:id屬性:對象唯一標(biāo)識时鸵。注意:對個id對應(yīng)的是同一個類對象
? ? ? ? ? name:屬性:唯一的標(biāo)識厅瞎。注意:多個name對應(yīng)是是不同的對象
? ? ? ? ? class:要管理的類的全類名
? ? ? ? ? scope:設(shè)定bean對象的作用域可選(singleton/prototype)
? ? ? ? ? prototype(原型模式),每次通過容器的getBean方法獲取prototype定義的Bean時和簸,都將產(chǎn)生一個新的Bean實例。
? ? ? ? ? singleton作用域的 Bean锁保,每次請求該Bean都將獲得相同的實例薯酝。
? ? ? ? ? ? ? lazy-init:設(shè)定bean元素是否要延遲初始化,可選屬性:(true:延遲初始化在getBean方法調(diào)用時才生成類對象/ false:非延遲初始化(默認(rèn)值)在容器加載過程中就進(jìn)行初始化)
- 進(jìn)程到以上基本工作就完成了蜜托,剩下的就是再test包下編寫一個測試類:
public class test {
public static void main(String[] args) {
//加載IOC容器:Spring容器相對于src對路徑
Resource resource = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
FirstBean first = (FirstBean)factory.getBean("first");
first.sayHello();
}
}
也可以使用如下方法:
public class test {
public static void main(String[] args) {
//加載IOC容器:Spring容器相對于src對路徑
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
FirstBean first = (FirstBean)app.getBean("first");
first.sayHello();
}
}
關(guān)于ApplicationContext和BeanFactory的區(qū)別:
- ApplicationContext是BeanFactory的一個子接口,是相對高級的容器的實現(xiàn)橄务。
- ApplicationContext:非延遲初始化容器,能盡可能早的發(fā)現(xiàn)程序的錯誤蜂挪。
運行結(jié)果如下:
下一篇:Spring依賴注入