1、把以下 jar 包加入到工程的 classpath 下:
commons-logging-1.1.1.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
2、Spring 的配置文件:一个典型的 Spring 项目需要创建一个或多个 Bean 配置文件,这些配置文件用于在 Spring IOC 容器里配置 Bean。Bean 的配置文件可以放在 classpath 下,也可以放在其它目录下。
3、测试:
创建bean
public class HelloWorld {
private String name;
public HelloWorld() {
System.out.println("HelloWorld's Constructor...");
}
public void setName2(String name) {
System.out.println("setName2: "+name);
this.name = name;
}
public void hello(){
System.out.println("Hello: " + name);
}
}
向Spring中注册bean
<!-- 配置一个 bean -->
<bean id="helloWorld" class="com.atguigu.spring.helloworld.HelloWorld">
<!-- 为属性赋值,对应属性的set方法-->
<property name="name2" value="Spring"></property>
</bean>
在创建 IOC 容器容器时,会调用 HelloWorld 的构造器创建对象,并调用set方法为属性赋值
public class Main {
public static void main(String[] args) {
//1. 创建 IOC 容器
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//2. 从 IOC 容器中获取 bean 实例
HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");
//3. 调用 bean 的方法
helloWorld.hello();
}
}