四时宝库

程序员的知识宝库

Idea中找不到Java Application 的xml配置文件问题研究

问题:

在用Idea建立一个Java Application工程的时候,应用了Spring框架,可是Spring的xml配置文件找不到。检查表明不是代码的问题。费了我好长时间才解决。

出现问题,我对Idea中加载各种资源文件(.xml、.properties等)做了研究总结。为了说明问题,下面建立一个Spring的test工程,目标就是运行后在控制台打印一个“Hello World!”,着重看Idea中资源的配置方法。以及不同配置方法会引起的不用效应。

环境:

IntelliJ IDEA 5.1.2 (我认为最好用的版本,现在7.0刚出来)

J2SDK 1.5

Spring framework 1.2.8

WIN2003

搭建测试项目:

依赖的包

commons-logging.jar

spring-beans.jar

spring-context.jar

spring-core.jar

源代码:

1、Bean类HelloBean :

public class HelloBean {

private String helloWord;

public void setHelloWord(String helloWord) {

this.helloWord = helloWord;

}

public String getHelloWord() {

return helloWord;

}

}

2、主类SpringDemo :

public class SpringDemo {

// public static void main(String[] args) {

// Resource rs =

// new FileSystemResource("beans-config.xml");

// BeanFactory factory =

// new XmlBeanFactory(rs);

//

// HelloBean hello =

// (HelloBean) factory.getBean("helloBean");

// System.out.println(hello.getHelloWord());

// }

public static void main(String args[]){

// ApplicationContext context = new FileSystemXmlApplicationContext("beans-config.xml");

ApplicationContext context = new ClassPathXmlApplicationContext("beans-config.xml");

HelloBean hello = (HelloBean)context.getBean("helloBean");

System.out.println(hello.getHelloWord());

}

}

3、Spring的配置文件beans-config.xml:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"

"[url]http://www.springframework.org/dtd/spring-beans.dtd[/url]">

<beans>

<bean id="helloBean"

class="lavasoft.springtest.HelloBean">

<property name="helloWord">

<value>Hello World!</value>

</property>

</bean>

</beans>

Idea配置:

下面是Idea项目的目录结构:

配置jar和资源文件:

目录类型设置图:

按照上图配置后,运行结果如下:

研究结果:

目录有三种类型,在图中已经给出了文字说明。

下面主要看res目录:

1、这个目录一般命名为res,以表示资源。

2、若这个目录设置为“Sources”类型,则在工程编译后,resorce目录下的文件会原封不动的复制到编译后生成文件的目录,在此为classes目录,并且在Idea的工程面板中可以看到res目录的存在。

3、这个目录设置为普通文件夹类型(浅黄色的文件包),则在工程编译后,resorce目录下的文件不会复制到classes目录,并且在Idea的工程面板中看不到此目录。

4、res目录下的文件要能被程序找到,则需要在Idea中配置res目录到classpath下面。参看第二个图。

5、这个配置方法适合其他的类型的配置文件比如.properties文件,原理就是将这些文件加载到calsspath中,这样就可以在Idea中调试运行了。

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接