Spring3开发实战 之 第二章:IoC/DI开发(2)(三)

2014-11-24 08:36:51 · 作者: · 浏览: 2
DispatcherServlet的web应用才能使用

示例,Java类:

java代码:
[java]
public class T2 implements ApplicationListener{
@Override
public void onApplicationEvent(ApplicationEvent arg0) {
System.out.println("事件发生了=="+arg0);
}
}

配置文件

Resource 接口 :
Spring的 Resource 接口是为了提供更强的访问底层资源能力的抽象,典型的是访问文件资源。基本的定义如下:

java代码:
[java]
public interface Resource extends InputStreamSource {
boolean exists();
boolean isOpen();
URL getURL() throws IOException;
File getFile() throws IOException;
Resource createRelative(String relativePath) throws IOException;
String getFilename();
String getDescription();
}
public interface InputStreamSource {
InputStream getInputStream() throws IOException;
}
可以使用ApplicationContext直接访问资源,示例如下:

java代码:
[java]
InputStream in = context.getResource("msg_en_GB.properties").getInputStream();
byte bs[] = new byte[100];
in.read(bs);
System.out.println("file content=="+new String(bs));
也可以向Bean里面注入资源,示例如下:
在Java类当中添加:

java代码:
[java]
private Resource rs = null;
public void setRs(Resource rs){
this.rs = rs;
}
在配置文件中:

java代码:
[java]



ApplicationContext能以声明的方式创建,在web.xml中配置如下:

java代码:
[java] www.2cto.com

contextConfigLocation
/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml


org.springframework.web.context.ContextLoaderListener

作者:jinnianshilongnian