做第一个Spring入门程序
我们需要创建一个动态web程序
在Eclipsec里的操作如下
再把
commons-logging-1.2.jar
spring-beans-4.3.6.RELEASE.jar
spring-context-4.3.6.RELEASE.jar
spring-core-4.3.6.RELEASE.jar
spring-expression-4.3.6.RELEASE.jar
四个jar包复制到 lib下
Spring框架包可以从https://download.csdn.net/download/gaogaosen/41211982
获取
在src下创建com.mao.ioc包
在com.map.ioc下创建Preson接口,并写一个say()方法
在com.map.ioc下创建Preson接口的实现类Man,并写一个say()方法
在com.map.ioc下创建Preson接口的实现类Woman,并写一个say()方法
在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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="Man" class="com.mao.ioc.Man" />
<bean id="Woman" class="com.mao.ioc.Woman" />
</beans>
把Man类在 applicationContext.xml里创建成一个id为Man的bean,class为Man的路径,Woman也如此
在com.map.ioc创建Spring测试类SpringText
public class SpringText {
public static void main(String[] args) {
//先获取能得到applicationContext.xml里bean的对象app
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
//然后用app去调用getBean方法得到applicationContext.xml里想用的bean
//作为一个Person我想作为男人一样说话
Person person=(Person) app.getBean("Man"); //我被赋值成了男人这个对象
person.say();//可以调用男人说法的方法了
//女人也如此
person=(Person) app.getBean("Woman");
person.say();
//好像我这两句也一样的效果,别急,学得越多才知道Spring的好处
Man man=new Man();
man.say();
}
}
运行结果为:
别急,学得越多才知道越多