新建配置文件
- 新建 Spring配置文件,名字随意,一般是命名applicationContext.xml,位置随意,建议还是放在src目录下。使用IDEA的话添加Spring模块的话是会自动生成这个配置文件的,使用Eclipse安装STS(Spring Tool Suite)插件,这个插件专门用于Spring开发的,安装了这个插件后,点击File->New->Others里面选择
- 引入约束,这个步骤可能有点复杂。但是用好开发工具就会很简单了,IDEA会自动引入约束,Eclipse在安装好STS(Spring Tool Suite)插件后在配置文件会出现一个Namespaces选项,要导入哪些约束自己√中,beans是一定要选中
简单的配置文件
写Spring配置文件要对Spring框架有个大体了解,Spring核心容器就是个大工厂,所有的对象都会当成Spring核心管理的对象———称之为Bean。
Spring容器的Bean与Java Bean不同,JavaBean必须遵守一些规范,而Spring对Bean没有要求,只要是Java类,Spring就可以管理该类,当成Bean处理。如何管理这些Bean,就需要通过写配置文件了。下面是一个简单配置文件的例子
- 新建一个简单类
package com.springday.bean; public class SimpleTest { public void test() { System.out.println("输出信息----"); } }
- applicationContext.xml配置上面Bean的信息
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 配置名为 simpleTest的bean,其实现类是com.springday.bean.SimpleTest--> <bean name="simpleTest" class="com.springday.bean.SimpleTest"></bean> </beans>
- 测试从Spring容器中获取该对象
package com.springday.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.springday.bean.SimpleTest; public class Demo { @Test public void fun1() { // 读取配置文件,创建容器对象 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); // 向容器要simpleTest对象 SimpleTest st = (SimpleTest) ac.getBean("simpleTest"); //输出信息 st.test(); } }