1.Spring IOC入门案例
A.添加spring开发环境
B.编写spring与DAO
C.编写配置文件,将service与dao交给spring管理
D.测试
//加载classPath下的文件
//ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
ApplicationContext ac = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"});
//加载磁盘中的配置文件-可以直接加载一个数组
ApplicationContext ac = new FileSystemXmlApplicationContext("src/applicationContext.xml");
1.2三种实例化Bean的方式
A.<bean id="studentDAO" class="cn.wang.spring.dao.StudentDAOImpl"/>
B.静态工厂方法:
public class StudentStaticFactory {
public StudentStaticFactory() {
}
private static Student stu;
//恶汉式
static {
stu = new Student();
}
public static Student getStudentByStaticFactoryMethod() {
return stu;
}
}
<!-- 静态工厂的方法 -->
<bean id="studentstaticFactory" class="cn.wang.spring.factory.StudentStaticFactory"
factory-method="getStudentByStaticFactoryMethod">
<property name="id" value="1"></property>
<property name="name" value="威哥"></property>
</bean>
C.实例工厂方法:
public class StudentInstanceFactory {
public Student getStudentByFactoryMethod() {
return new Student();
}
}
<!-- 注册实例工厂Bean -->
<bean id="studentInstanceFactory" class="cn.wang.spring.factory.StudentInstanceFactory"/>
<bean id="student3" factory-bean="studentInstanceFactory" factory-method="getStudentByFactoryMethod">
<property name="id" value="2"/>
<property name="name" value="大卫"></property>
</bean>
2.Spring容器管理对象的模式:
默认是单例模式,可以通过bean标签的scope进行修改
prototype:每次调用返回一个新的对像
request:每一个新的请求创建一个新的对象
session:同一个回话公用一个session
3.Bean的声明周期:
init-method="init"
destroy-method="destroy"(只有在单利模式下才有效)
1.加载配置文件,初始化容器
2.将Bean对象加入到容器中进行管理(init。。。方法)
3.通过程序获得JavaBean对象。。
4.执行destroy。。。
4.依赖注入:
1.setter注入:
JavaBean中保留无参构造,对成员变量添加setter方法
2.构造注入:
通过构造方法进行注入
<bean id="student5" class="cn.wang.spring.bean.Student">
<constructor-arg index="0" value="1"></constructor-arg>
<constructor-arg index="1" value="赵丽颖"></constructor-arg>
</bean>
对比:
1.类结构:setter,无参构造方法
2.实时性:构造方法实时性更高,在初始化当前对象时注入依赖对象。
setter注入,在初始化当前对象后,调用setter方法完成依赖对象的注入.
3.p命名空间注入:
p:属性名="";
p:属性名-ref="bean的id";
使用默认无参构造完成初始化!
4.自动注入:
1.byName:
autowire="byName"
通过查找与当前Bean成员变量名称相同的beanid,查找到注入。
如果查找不到不注入,走默认值,可能产生空指针异常
2.byType
autowire="byType"
通过查找与当前Bean成员类型相同的beanid,查找到注入。
要求匹配的bean只能有一个,如果多个,异常
5.注解注入(本质上是setter注入,但是可以省略setter方法)
表示Bean的注解:
@Component
@Repository :用于标注DAO类
@Service :用于标注业务类
@Controller :用于标注控制器类
范围标签
@scope() 用来标识当前bean的范围
注入标签
@Autowired:默认使用byType方式注入:容易引起异常
通过ByName注入:
@Autowired(required=true)
@Qualifier("studentDAO2Impl")
@Autowired可以作用在成员变量和setter方法上
@Resource(推荐使用)
默认使用byType方式注入:容易引起异常
byName:
@Resource(name="beanId")
1.使用注解推荐为所有的bean定义id,默认值驼峰类名
2.必须定义扫描的基包:
A.引入命名空间
B.设置扫描包
<!-- 扫描注解的基包 -->
<context:component-scan base-package="cn.wang.spring"/>