1.新建项目Flie—New—Dynamic Web Project.
2.导入Spring 相关依赖包
3.在项目的java Resources/src 下创建com.itheima包,在包下创建HelloSpring的类,在HelloSpring类中定义userName的属性和show()方法。
package com.itheima;
//3.
public class HelloSpring {
private String userName;
public void setUserName(String userName) {
this.userName = userName;
}
public void show(){
System.out.println(userName+":欢迎来到Spring");
}
}
4.在项目的java Resources/src 下创建ac.xml作为HelloSpring类的配置文件。
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置HelloSpring类,让Spring自动创建HelloSpring的实例 -->
<!-- id:实例出类的id名 class:需要实例的类(全名) -->
<bean id="hs" class="com.itheima.HelloSpring">
<!-- property传值 name传值的属性名 value传递的值 -->
<property name="userName" value="zs"></property>
</bean>
</beans>
5.编写测试程序:在项目的java Resources/src 下创建com.app包,创建TestHelloSpring类,
package com.app;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.itheima.HelloSpring;
public class TestHelloSpring {
public static void main(String[] args) {
//生成容器
ApplicationContext ap = new ClassPathXmlApplicationContext("ac.xml");
//根据容器中的been的id取出bean
HelloSpring hs =(HelloSpring) ap.getBean("hs");
//调用方法
hs.show();
}
}
6.运行结果展示