准备工作:开发工具,spring的基本jar包。
编写文件:beans.xml,HelloWorld.java,MainApp.java
beans.xml主要内容:
放在src文件夹下面
<?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-4.3.xsd"> <bean id="helloWorld" class="com.tutorialspoint.HelloWorld"> <property name="message" value="Hello World!"/> </bean> </beans>1.配置XSD文件,简单的说是xml的一个标签的定义,在你下载的spring安装包的schema/beans/目录下,包含先前版本。
2.配置bean,id是使用这个bean的名称,class是bean对应的类,property是对应类已存在的属性,value是值。
HelloWorld.java主要内容:
放在自建的包下,要和beans.xml路径相对应
package com.tutorialspoint; public class HelloWorld { private String message; /** * @return the message */ public String getMessage() { return message; } /** * @param message the message to set */ public void setMessage(String message) { this.message = message; } }
一个属性和对应的getset方法。
MainApp.java主要内容:
与HelloWorld.java放到一起
package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); HelloWorld obj = (HelloWorld)context.getBean("helloWorld"); System.out.println(obj.getMessage()); } }
Application Context 是 spring 中较高级的容器。和 BeanFactory 类似,它可以加载配置文件中定义的 bean,将所有的 bean 集中在一起,当有请求的时候分配 bean。 另外,它增加了企业所需要的功能,比如,从属性文件从解析文本信息和将事件传递给所指定的监听器。这个容器在 org.springframework.context.ApplicationContext interface 接口中定义。
ClassPathXmlApplicationContext类用于加载beans.xml文件,*注意:在多个配置位置的情况下,以后的bean定义将
重写先前加载文件中定义的文件。
运行MainApp.java。