一、在Spring诞生之前,也有一个容器叫EJB 现在有些公司都还在用此容器。此容器它是重量级的,而且侵入性非常强,所谓侵入性就是必须继承或者实现指定的类和接口,而且卖的也非常贵。
Spring是一个轻量级的IoC和AOP容器框架:
a、轻量级:程序实现不是很复杂,代码不是很多,占用资源不是很多,没有侵入性;(通常不要求继承特定类或者实现特定接口);
b、IoC(Inversion of Control 控制反转):对象创建责任的反转(重点,核心); Dependency Injection (DI)依赖注入;
c、Aop(Aspect Oriented Programming):一种面向横切面编程的思想方式,可以进行功能性扩展 ,面向横切面(AOP)编程;
d、容器:可以容纳对象,并且可以控制对象的生命周期;
二、使用步骤
1、创建一个java项目,并在项目中创建lib文件,将spring的jar包及spring依赖的jar包放入lib文件中,选中所有jar包鼠标右键Build Path;(注意:spring的jar包及spring依赖的jar包去官网下载即可)
2、右键点击项目工程--Myeclipse--project facets--install spring facet--Add Spring Capabilites...,创建编写框架的核心配置文件,存放在src目录下:applicationContext.xml;
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
</beans>
三、setter注入
这是最简单的注入方式
1、首先创建好三个类:User、User1、User2
package cn.com.beans;
public class User1 {
public void ceshi1() {
System.out.println("User1的ceshi1方法!");
}
}
package cn.com.beans;
public class User2 {
public void ceshi2() {
System.out.println("User2的ceshi2方法!");
}
}
package cn.com.beans;
public class User {
private User1 user1; //User1类
private User2 user2; //User2类
//创建属性的get,set方法
public User1 getUser1() {
return user1;
}
public void setUser1(User1 user1) {
this.user1 = user1;
}
public User2 getUser2() {
return user2;
}
public void setUser2(User2 user2) {
this.user2 = user2;
}
public void ceshi() {
user1.ceshi1();
user2.ceshi2();
System.out.println("User的ceshi方法!");
}
}
2、在配置文件applicationContext.xml中注入
<!--配置bean,配置后该类由spring管理-->
<bean id="user" class="cn.com.beans.User" autowire="byType"></bean>
<!--(1)依赖注入,配置当前类中相应的属性-->
<property name="springDao" ref="springDao"> </property> </bean>
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!-- 将实体类注入Spring容器,class为实体类的全路径 -->
<bean id="user" class="cn.com.beans.User" autowire="byType"></bean>
<bean id="user1" class="cn.com.beans.User1"></bean>
<bean id="user2" class="cn.com.beans.User2"></bean>
</beans>
3、编写测试类
package cn.com.beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
//new一个ClassPathXmlApplicationContext对象,将它负值给ctx
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//调用getBean()方法,User.class是实体类的映射,user是applicationContext.xml中注入类的id
User user=ctx.getBean(User.class, "user");
//调用实体类中的ceshi()方法
user.ceshi();
}
}
4、测试结果