**
Spring的一次实例
1.新建一个空的项目命名test
2.导入必要的jar包
3.在pakge下新建一个Source类
package pojo;
public class Source {
private String fruit; // 类型
private String sugar; // 糖分描述
private String size; // 大小杯
public String getFruit(){
return fruit;
}
public String getSugar(){
return sugar;
}
public String getSize(){
return size;
}
public void setFruit(String fruit){
this.fruit=fruit;
}
public void setSugar(String sugar){
this.sugar=sugar;
}
public void setSize(String size){
this.size=size;
}
}
4.在src下目录下新建一个applicationContext.xml文件通过 xml 文件配置的方式装配我们的 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="source" class="pojo.Source">
<property name="fruit" value="橙子"/>
<property name="sugar" value="多糖"/>
<property name="size" value="超大杯"/>
</bean>
</beans>
5.在packge下新建一个testspring
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.Source;
import pojo.juiceMaker;
public class testspring {
@SuppressWarnings("resource")
public static void main(String args[]){
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
Source source=(Source)context.getBean("source");
System.out.println(source.getFruit());
System.out.println(source.getSugar());
System.out.println(source.getSize());
}
}
5.运行结果如下
**
**
DI依赖注入实例
指 Spring 创建对象的过程中,将对象依赖属性(简单值,集合,对象)通过配置设值给该对象
继续上述代码
1.在packge下新建一个juiceMaker类
package pojo;
public class juiceMaker {
private Source source=null;
public Source getSource(){
return source;
}
//set必须小写
public void setSource(Source source){
this.source=source;
}
public String makeJuice(){
String juice="sp点了一杯"+source.getFruit()+source.getSugar()+source.getSize();
return juice;
}
}
2.在 xml 文件中配置 JuiceMaker 对象
<?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="source" class="pojo.Source">
<property name="fruit" value="橙子"/>
<property name="sugar" value="多糖"/>
<property name="size" value="超大杯"/>
</bean>
<bean name="juiceMaker" class="pojo.juiceMaker">
<property name="source" ref="source" />
</bean>
</beans>
3.testspring的main改成
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[]{"applicationContext.xml"}
);
Source source = (Source) context.getBean("source");
System.out.println(source.getFruit());
System.out.println(source.getSugar());
System.out.println(source.getSize());
JuiceMaker juiceMaker = (JuiceMaker) context.getBean("juickMaker");
System.out.println(juiceMaker.makeJuice());
}
结果如下
**