spring 理解
- IoC () :控制反转,当新建了一个java类,正常使用是在代码中使用 new 创建一个java对象实例,在spring中,使用配置文件来管理和创建 java对象(实例)。需要用到时,不需要使用 new 创建,而是通过spring 在容器中拿到一个对象
- DI ()依赖注入,在一个类中拥有另外一个类,或者说拥有另外一个类的属性,给这个属性赋值的过程我理解为依赖注入,在spring之前这个注入可以通过 seter 方法完成,spring中,依赖注入依然可以交给配置文件来完成。
- is a 是一个 → 继承
- has a 有一个 → 依赖(组合)
-
spring装配bean
两种方式:
一:xml文件配置bean,xml文件配置,可以根据 类属性的类型(type),名字,构造方法自动装备bean
另外在类的属性(字段),构造方法,set方法上使用注解 @Autowired 也可以实现自动装备
@Autowired的使用:
使用 @Autowired ,需要注册 AutowiredAnnotationBeanPostProcessor。两种方式
① 配置文件中直接包含
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
② Include <context:annotation-config />
在配置文件头部添加
<beans
//...
xmlns:context="http://www.springframework.org/schema/context"
//...
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
//...
<context:annotation-config />
//...
</beans>
二:javaConf配置bean : 使用java文件配置bean
测试实例:
一,创建项目 testIoC
测试点:从配置文件拿到bean(实体类)
package com.cn.entity;
public class User {
private String userName ;
public User() {
// TODO 自動生成されたコンストラクター・スタブ
}
public User(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
testIoC.xml
配置文件配置bean,需要bean保留无参构造函数,没有的话会报错【No default constructor found; nested exception is。。。】
<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">
<bean id="userServices" class="com.cn.entity.User">
<property name="userName" value="小明"/>
</bean>
</beans>
TestGetBean.java
package com.cn.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.cn.entity.User;
public class TestGetBean {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("testIoC.xml");
User user = (User) context.getBean("userServices");
System.out.println(user.getUserName());
}
}
运行结果: 小明