使用Spring創建第一個工程
- 導入spring的jar包
- 編寫bean的實現類
- src下創建beans.xml,其中添加<bean>標籤,指明id和class屬性
- 加載配置文件ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
- 從容器中獲取bean(需要強制類型轉換)context.getBean("bean的id");
例子
編寫UserBean,與數據庫中字段對應。
package cn.sdut.bean;
public class UserBean {
private int id;
private String username;
private int age;
public UserBean() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
編寫配置文件 beans.xml,其他的可以複製粘貼,在裏面添加bean標籤,id爲要使用時要獲取的bean對象名(具有唯一性),class爲pojo的全限定類名。
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<!-- 構造方法實例化 -->
<bean id="user" class="cn.sdut.bean.UserBean">
</bean>
</beans>
測試類Test
IoC獲取Bean的方式有兩種,
- ApplicationContext:啓動時將所有bean實例化,並且校驗xml文件的錯誤。
- BeanFactory:啓動時不校驗xml文件的錯誤,當獲取bean時,如果xml文件錯誤,會產生配置問題。
ApplicationContext 對於Bean是儘可能早的初始化,主要實現類爲
- ClassPathXmlApplicationContext
BeanFactory對於bean是儘可能晚的初始化。
- BeanFactory factory = new ClassPathXmlAppliactionContext("beans.xml");
- 主要方法 參數爲bean標籤裏的id
- Object getBean(String)
- boolean containsBean(String)
- boolean IsSingleton(String)
package cn.sdut.test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.sdut.bean.UserBean;
public class Test {
public static void main(String[] args) {
//第一次實例化時完成對象的創建
//使用spring容器獲取bean對象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//獲得UserBean對象
UserBean user = (UserBean) context.getBean("user");
//模擬從數據庫中取出數據
user.setUsername("hydra");
System.out.println(user.getUsername());
//延時創建,使用時創建
BeanFactory factory = new ClassPathXmlApplicationContext("beans.xml");
UserBean user1 = (UserBean) factory.getBean("user");
user1.setUsername("Hydra");
System.out.println(user1.getUsername());
}
}
Bean的定義
在beans.xml中<beans>標籤中加入<bean>標籤,其中的屬性
- id指明bean的id,具有唯一性
- class指明bean的實現類,全限定類名
- lazy-init 延遲加載,取值爲布爾值,表示bean在容器啓動時初始化還是第一次被請求時初始化。
- scope 範圍 取值爲bean的5種作用域,默認值是單例模式
- singleton 單例模式 (一直使用第一次創建好的,如果已經存在,不在創建新對象)
- prototype 每次從容器中get的bean對象都是新對象
- request
- session
- global session