4.3 Access Resource

Access Resource

1. ResourceLoader

Spring has a DefaultResourceLoader which can return ClassPathResource, UrlResource, and ServletContextResourceLoader which extends all functions of DefaultResourceLoader.

1
2
3
4
5
6
@Test
public void testResourceLoad() throws IOException {
ResourceLoader loader = new DefaultResourceLoader();
Resource resource = loader.getResource("classpath:cn/javass/spring/chapter4/test.txt");
Assert.assertEquals(ClassPathResource.class, resource.getClass());
}

Read More

4.2 Using Resource

Using Resource

1. ByteArrayResource

Junit test:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import org.junit.Test;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;

public class ResourceTest {

@Test
public void testByteArraryResorce() {
Resource resource = new ByteArrayResource("Hello World!".getBytes());
if (resource.exists()) {
dumpStream(resource);
}
Assert.assertEquals(false, resource.isOpen());
}

private void dumpStream(Resource resource) {
InputStream inputStream = null;
try {
inputStream = resource.getInputStream();
byte [] descByte = new byte [inputStream.available()];
inputStream.read(descByte);
System.out.println(new String(descByte));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Read More

3.2 Bean Scopes

Bean scopes: singleton and prototype

1. singleton

Only one instance in Spring IoC container. Only return the same Bean.

One instance of the bean is created for the entire application.

Two ways to implement, we could learn how Spring work through the code bellow:

  • Define static attribute to hold the instance:
1
2
3
4
5
6
7
8
9
10
11
12
13
package cn.javass.spring.chapter3.bean;  
public class Singleton {
//1. Private constructor
private Singleton() {}

private static class InstanceHolder {
private static final Singleton INSTANCE = new Singleton();
}
//3.Global accession
public static Singleton getInstance() {
return InstanceHolder.INSTANCE;
}
}

Read More