HelloSpring
任何语言都是从Hello开始,那么我们从HelloSpring开始认识Spring
代码
Hello Spring 直接从代码对Spring有一个整体的了解。
HelloWorld.java
package com.soygrow.HelloSpring;
public class HelloWorld {
private String message;
public void setMessage(String message) {
this.message = message;
}
public void getMessage() {
System.out.println("Your Message : " + message);
}
}
MainApp.java
package com.soygrow.HelloSpring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("HelloSpringBeans.xml");
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
helloWorld.getMessage();
}
}
HelloSpringBeans.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="helloWorld" class="com.soygrow.HelloSpring.HelloWorld">
<property name="message" value="Hello Soygrow!"/>
</bean>
</beans>
代码分析
关于MainApp有一下两点需要注意的:
- 第一步我们使用框架的API ClassPathXmlApplicationContext()
来创建应用程序的上下文。这个API加载beans的配置文件并最终基于所提供的API,它处理创建并初始化所有的对象,即将Beans.xml中的Bean初始化并生成对象。
- 第二步使用已创建的上下文的getBean()方法获得所需要的bean,这个方法使用bean的ID返回一个最终可以转换为实际对象的通用对象。一旦有了对象就可以调用任何属于它的方法。
Beans.xml用于给不同的bean分配一个唯一的ID,并且控制不同值的对象的创建,而不影响Spring的任何源文件。
遇到的问题
网上的教程,在自己的手里都会遇到各种各样的问题,所以这里记录自己遇到的问题。
- 找不到Beans.xml
使用IntelliJ IDEA创建Spring时,不会出现WEB-INF目录,如果自己创建该目录可能会提示下面信息,表示找不到xml文件。
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [Beans.xml];
nested exception is java.io.FileNotFoundException: class path resource [Beans.xml] cannot be opened because it does not exist
解决方法:
IntelliJ IDEA中 选中xml所在的目录右键->Make Directory as->Reource roots