使用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