spring框架最初设计于2003年,作为J2EE开发的轻量级解决方案,目前已经成为构建企业级应用的标准选择和Java开发人员的必备工具。迄今为止Spring 5是最新的主版本。
* Spring特点 *
- 简化Java开发,代替重量级的Java开发技术。如EJB。
- 开源
- 低侵入性
package cn.wind.spring;
//动物类
public interface Animal {
void say();
}
package cn.wind.spring.impl;
import cn.wind.spring.Animal;
public class Dog implements Animal {
public Dog() {
System.out.println("Dog constructor...");
}
public void say() {
System.out.println("wang-wang-wang...");
}
}
package cn.wind.spring.impl;
import cn.wind.spring.Animal;
public class Cat implements Animal {
public Cat() {
System.out.println("Cat constructor...");
}
public void say() {
System.out.println("miao-miao-miao...");
}
}
package cn.wind.spring.impl;
import cn.wind.spring.Animal;
public class sheep implements Animal {
public void say() {
System.out.println("mie-mie-mie...");
}
}
package cn.wind.spring;
public class Zoo {
private Animal dog;
private Animal cat;
private Animal sheep;
public Zoo(Animal sheep) {
this.sheep = sheep;
}
public void setSheep(Animal sheep) {
this.sheep = sheep;
}
public void setDog(Animal dog) {
this.dog = dog;
}
public void setCat(Animal cat) {
this.cat = cat;
}
public void speak() {
dog.say();
cat.say();
sheep.say();
}
}
package cn.wind.spring;
import org.springframework.context.support.ClassPathXmlApplicationContext;
//测试类
public class test {
public static void main(String[] args) {
//加载Spring上下文(Spring ApplicationContext负责bean对象的创建与组装)
// ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean对象
Zoo zoo = (Zoo) context.getBean("zoo");
zoo.speak();
context.close();
}
}
#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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="dog" class="cn.wind.spring.impl.Dog"></bean>
<bean name="cat" class="cn.wind.spring.impl.Cat"></bean>
<bean name="sheep" class="cn.wind.spring.impl.sheep"></bean>
<bean name="zoo" class="cn.wind.spring.Zoo">
<property name="dog" ref="dog"/>#setter注入
<property name="cat" ref="cat"/>
<constructor-arg ref="sheep"/>#构造注入
</bean>
</beans>