- 创建项目工程,增加项目的依赖包
- 创建Spring的配置文件
创建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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
</beans>
- Spring配置文件配置,编写相关应用程序
范例: 编写程序,向指定的人问候,指定的人由Spring的配置文件获取
package com.oupeng;
public class HelloSpring {
private String who="";
public String getWho() {
return who;
}
public void setWho(String who) {
this.who = who;
}
public void print() {
System.out.println("你好"+this.getWho());
}
}
配置文件配置具体的人:
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<!-- 配置一个bean id唯一标识符,class完整类名 -->
<bean id="HelloSpring" class="com.oupeng.HelloSpring">
<!-- 配置属性 -->
<property name="who">
<value>Spring!!!</value>
</property>
</bean>
</beans>
- 测试
@Test
public void test1(){
//加载Spring的配置文件
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean,创建bean 原来使用kkk m=new kkk();这种方式,现在使用bean方式,spring负责在调用bean的时候创建对象
HelloSpring hello=(HelloSpring) context.getBean("HelloSpring");//写配置文件id
/**
* HelloSpring hello=new HelloSpring();
* hello.setWho("spring!!!");
* 之前的方式
*
*/
//调用业务逻辑方法
hello.print();
//和之前最大的区别不用new,创建交给spring去处理
}
执行结果
你好Spring!!!