Spring学习-第一篇:关于读取配置文件
最近在用Spring大法的框架,便利了我们,但是对于内部完全不知,虽然满足正常业务需求,但是一旦出现问题,解决效率太低,所以准备深入学习一下,准备个一系列,有不对的地方希望大家多多提建议!
#读取配置,从applicationContext.xml谈起
spring如果脱离了注解,开发效率肯定下降一大步,但是我们为了学习内部,就慢慢来了。
开发工具用IDEA,用spring官方初始化模板,建的一个spring boot项目,(项目类型无关紧要,我们要学的是根本,其实是懒),一般Java spring项目都是在WEB-INF目录下,不过这个项目不同,大家可以稍微注意下,resources放配置文件,
public class Monkey { private String monkeyName = "MonkeyKing"; public String toString(){ return "MonkeyName:" + monkeyName; } }
public class Tiger { private String tigerName="TigerKing"; public String toString(){ return "TigerName:"+tigerName; } }
public class Zoo { private Tiger tiger; private Monkey monkey; public String toString(){ return tiger + "\n" + monkey; } }
applicationContext.xml 位于resources目录下
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <bean id="zoo" class="com.example.Zoo" > <property name="tiger" ref="tiger" ></property> <property name="monkey" ref="monkey" ></property> </bean> <bean id="tiger" class="com.example.Tiger" /> <bean id="monkey" class="com.example.Monkey" /> </beans>
测试类:
public class MainTest { /** * 不使用注解 */ @Test public void test(){ //读取配置文件 ApplicationContext ctx = new FileSystemXmlApplicationContext("src/main/resources/applicationContext.xml"); Zoo zoo = (Zoo) ctx.getBean("zoo"); System.out.println(zoo.toString()); } }
大家注意,我用的是 FileSystemXmlApplicationContext 来加载配置文件
还可以用 ClassPathXmlApplicationContext
ApplicationContext ctx =
new ClassPathXmlApplicationContext("applicationContext.xml");
注意 FileSystemXmlApplicationContext引用的是具体文件系统的文件路径,而ClassPathXmlApplicationContext
在classpath找到xml文件
这其中有个关键点:classpath
我们先看下这个路径
String s[] = System.getProperty("java.class.path").split(";"); for (String string : s) { System.out.println(string); }
可以获取到当前项目工作目录:D:\gitwork\SpringTest\target\classes
所以,可以看到,我们的classpath是在build目录下:
因为我是springboot项目,所以resources目录独立出来了,普通Java项目会在WEB-INFO/classes下。
@Test public void test(){ //读取配置文件 ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); Zoo zoo = (Zoo) ctx.getBean("zoo"); System.out.println(zoo.toString()); }
这样 我们就能读取 applicationContext.xml文件了
转载于:https://www.cnblogs.com/haoming1100/articles/6866993.html