搭建 Spring 开发环境
把以下 jar 包加入到下:
工程的 classpath
Spring 的配置文件: 一个典型的 Spring 项目需要创建一个或多个 Bean 配置文件, 这些配置文件用于在 Spring IOC 容器里配置 Bean. Bean 的配置文件可以放在 classpath 下, 也可以放在其它目录下.
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
id:bean的唯一标识
class:指定全类名 反射的方式创建对象:
Class cls = Class.forName("com.learn.spring.beans.HelloWorld")
Object obj = cls.newInstance(); // 需要提供默认的构造器.
property: 通过set方法给指定的属性赋值
-->
<bean id="helloWorld" class="com.learn.spring.beans.HelloWorld">
<property name="name1" value="Jerry"></property>
</bean>
</beans>
package com.learn.spring.beans;
public class HelloWorld {
private String name ;
public HelloWorld() {
System.out.println("invoke HelloWorld Constructor.....");
}
public String getName() {
return name;
}
public void setName1(String name) {
System.out.println("invoke HelleWorld setName......");
this.name = name;
}
public void sayHello(){
System.out.println("my name 's " + name );
}
}
package com.learn.spring.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
/*//1.new 对象
HelloWorld helloWorld = new HelloWorld();
//2.给name属性赋值
helloWorld.setName("Tom");
*/
//1.获取IOC容器
ApplicationContext ctx =
new ClassPathXmlApplicationContext("applicationContext.xml");
//2.从IOC容器中获取对象.
//HelloWorld helloWorld = (HelloWorld)ctx.getBean("helloWorld");
//3.调用方法
helloWorld.sayHello();
}
}