Spring Resource
java.net.URL์ ํ๊ณ๋ฅผ (classpath ๋ด๋ถ ์ ๊ทผ์ด๋ ์๋๊ฒฝ๋ก ๋ฑ) ๋์ด์๊ธฐ ์ํด ์คํ๋ง์์ ์ถ๊ฐ๋ก ๊ตฌํ
Resource Interface์ ๊ทธ ๊ตฌํ์ฒด๋ค
public interface Resource extends InputStreamSource {
boolean exists();
boolean isReadable();
boolean isOpen();
boolean isFile();
URL getURL() throws IOException;
URI getURI() throws IOException;
File getFile() throws IOException;
ReadableByteChannel readableChannel() throws IOException;
long contentLength() throws IOException;
long lastModified() throws IOException;
Resource createRelative(String relativePath) throws IOException;
String getFilename();
String getDescription();
}
Resource ๊ตฌํ์ฒด ๋ชฉ๋ก
Spring ๋ด๋ถ Resource ๊ตฌํ์ฒด ์ค ๋ํ์ ์ธ ๋ช๊ฐ์ง
UrlResource
java.net.URL ์ ๋ํํ ๋ฒ์ , ๋ค์ํ ์ข ๋ฅ์ Resource ์ ์ ๊ทผ ๊ฐ๋ฅํ์ง๋ง ๊ธฐ๋ณธ์ ์ผ๋ก๋ http(s) ๋ก ์๊ฒฉ ์ ๊ทผ (ftp:, file:, http:, ๋ฑ์ prefix ๋ก ์ ๊ทผ์ ํ ํ๋จ)
ClassPathResource
classpath ํ์์ ๋ฆฌ์์ค ์ ๊ทผ ์ ์ฌ์ฉ (์์ค์ฝ๋๋ฅผ ๋น๋ํ ๊ฒฐ๊ณผ(๊ธฐ๋ณธ์ ์ผ๋ก target/classes ํด๋))
FileSystemResource
File ์ ๋ค๋ฃจ๊ธฐ ์ํ ๋ฆฌ์์ค ๊ตฌํ์ฒด
SevletContextResource, InputStreamResource, ByteArrayResource
Servlet ์ดํ๋ฆฌ์ผ์ด์ ๋ฃจํธ ํ์ ํ์ผ, InputStream, ByteArrayInput ์คํธ๋ฆผ์ ๊ฐ์ ธ์ค๊ธฐ ์ํ ๊ตฌํ์ฒด
Spring ResourceLoader
์คํ๋ง ํ๋ก์ ํธ ๋ด Resource ์ ์ ๊ทผํ ๋ ์ฌ์ฉํ๋ ๊ธฐ๋ฅ
๊ธฐ๋ณธ์ ์ผ๋ก applicationContext ์์ ๊ตฌํ์ด ๋์ด ์์
ํ๋ก์ ํธ ๋ด ํ์ผ์ ์ ๊ทผํ ์ผ์ด ์์ ๊ฒฝ์ฐ ํ์ฉ (์ฃผ๋ก classpath ํ์ ํ์ผ)
๋๋ถ๋ถ์ ์ฌ์ ์ ์๋ ํ์ผ๋ค์ ์๋์ผ๋ก ๋ก๋ฉ๋๋๋ก ๋์ด ์์ผ๋, ์ถ๊ฐ๋ก ํ์ํ ํ์ผ์ด ์์ ๋ ํ์ฉ ๊ฐ๋ฅ
@Service
public class ResourceService {
@Autowired
ApplicationContext ctx;
public void setResource() {
Resource myTemplate =
ctx.getResource("classpath:some/resource/path/myTemplate.txt");
// ctx.getResource("file:/some/resource/path/myTemplate.txt");
// ctx.getResource("http://myhost.com/resource/path/myTemplate.txt");
// use myTemplate...
}
}
ResourcePatternResolver
์คํ๋ง ApplicationContext ์์ ResourceLoader ๋ฅผ ๋ถ๋ฌ์ฌ ๋ ์ฌ์ฉํ๋ Interface ์์น ์ง์ ์ ํจํด์ ๋ฐ๋ผ ์๋์ผ๋ก Resouce ๋ก๋ ๊ตฌํ์ฒด๋ฅผ ์ ํ ("classpath:", "file:", "http:")
public interface ApplicationContext extends EnvironmentCapable,
ListableBeanFactory, HierarchicalBeanFactory,
MessageSource, ApplicationEventPublisher, **ResourcePatternResolver** {
// Spring ApplicationContext interface
}
Application Contexts & Resource Paths
applicationContext ๋ฅผ ์ด๋ฃจ๋ ์ค์ ๊ฐ์ ๊ฐ์ ธ์ค๋ ๋ฐฉ๋ฒ๋ค
// let's create an applicationContext
ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml");
ApplicationContext ctx =
new FileSystemXmlApplicationContext("conf/appContext.xml");
ApplicationContext ctx =
new FileSystemXmlApplicationContext("classpath:conf/appContext.xml");
// then you can use ctx as a Spring
Bear bear = (Bear) ctx.getBean("bear");
Last updated
Was this helpful?