一 概述
二.代码
1.导入jar包
2.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" xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloJava" class="com.blueSky.test.HelloJava">
<property name="content" value="你好,java" />
</bean>
<bean id="helloWorld" class="com.blueSky.test.HelloWorld">
<property name="content" value="你好,世界" />
<property name="helloJava" ref="helloJava"></property>
</bean>
</beans>
3.编写java类
package com.blueSky.test;
public class HelloJava {
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
package com.blueSky.test;
public class HelloWorld {
private String content; //输出的内容
private HelloJava helloJava;
public HelloJava getHelloJava() {
return helloJava;
}
public void setHelloJava(HelloJava helloJava) {
this.helloJava = helloJava;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
/*
* 输出content 和 helloJava对象的content
* */
public void printContent(){
System.out.println(content);
System.out.println(helloJava.getContent());
}
}
4.applicationContext.xml文件中配置< bean >标签
<?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"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloJava" class="com.blueSky.test.HelloJava">
<property name="content" value="你好,java" />
</bean>
<bean id="helloWorld" class="com.blueSky.test.HelloWorld">
<property name="content" value="你好,世界" />
<property name="helloJava" ref="helloJava"></property>
</bean>
</beans>
5.测试
package test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.blueSky.test.HelloWorld;
public class SpringTest {
@Test
public void test1() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
helloWorld.printContent();
}
}
6.错误分析
web.xml配置
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>